import {
  SESv2Client,
  PutSuppressedDestinationCommand,
  DeleteSuppressedDestinationCommand,
  SuppressionListReason,
  NotFoundException,
} from "@aws-sdk/client-sesv2";

import { env } from "@/config/env";
import { SesSuppressionProvider, SesSuppressionReason } from "./ses-suppression-provider";

let sharedClient: SESv2Client | null = null;

function getClient(): SESv2Client {
  if (!sharedClient) {
    sharedClient = new SESv2Client({
      region: env.awsRegion,
      credentials:
        env.awsAccessKeyId && env.awsSecretAccessKey
          ? { accessKeyId: env.awsAccessKeyId, secretAccessKey: env.awsSecretAccessKey }
          : undefined,
    });
  }
  return sharedClient;
}

export class SesSuppressionProviderImpl implements SesSuppressionProvider {
  async putSuppressedDestination(email: string, reason: SesSuppressionReason): Promise<void> {
    await getClient().send(
      new PutSuppressedDestinationCommand({
        EmailAddress: email,
        Reason: reason === "BOUNCE" ? SuppressionListReason.BOUNCE : SuppressionListReason.COMPLAINT,
      })
    );
  }

  async deleteSuppressedDestination(email: string): Promise<void> {
    try {
      await getClient().send(new DeleteSuppressedDestinationCommand({ EmailAddress: email }));
    } catch (error) {
      if (error instanceof NotFoundException) return;
      throw error;
    }
  }
}
