import sharp from 'sharp'
import { resolve } from 'path'
import { SESClient, SendEmailCommand } from '@aws-sdk/client-ses'
import dotenv from 'dotenv'
import fs from 'fs'

dotenv.config({ path: resolve(process.cwd(), '.env') })

// Ensure required environment variables exist
if (
  !process.env.AWS_ACCESS_KEY_ID ||
  !process.env.AWS_SECRET_ACCESS_KEY ||
  !process.env.S3_BUCKET ||
  !process.env.CLOUDFRONT_DOMAIN
) {
  throw new Error(
    'Missing required AWS environment variables [access key, secret, bucket name and cloudfront domain]',
  )
}

// Configure AWS SDK v3
const sesClient = new SESClient({
  region: process.env.AWS_REGION || 'us-east-1',
  credentials: {
    accessKeyId: process.env.AWS_ACCESS_KEY_ID,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
  },
})

interface EmailParams {
  toEmail: string
  subject: string
  body: string
  extraInfo?: Record<string, unknown>
}

/**
 * Resize an image (provided as a buffer) and upload it to S3.
 * @param {Buffer} fileBuffer - Image file as a buffer.
 * @param {number} width - Desired width.
 * @param {number} height - Desired height.
 * @param {string} outputKey - S3 object key (filename).
 * @returns {Promise<string>} - Returns the CloudFront URL of the uploaded file.
 */
export async function sendEmail({
  toEmail,
  subject,
  body,
  extraInfo,
}: EmailParams): Promise<{ message: string }> {
  try {
    // create an email body with provided body and extra info
    const emailBody = `${body}\n\nAdditional Information:\n${JSON.stringify(extraInfo, null, 2)}`

    const params = {
      Source: process.env.SES_FROM_EMAIL as string,
      Destination: {
        ToAddresses: [toEmail],
      },
      Message: {
        Subject: { Data: subject },
        Body: { Text: { Data: emailBody } },
      },
    }

    await sesClient.send(new SendEmailCommand(params))

    // Return the CloudFront URL
    return {
      message: `Email sent to ${toEmail}`,
    }
  } catch (error) {
    console.error('Error processing image:', error)
    throw error
  }
}
