import { S3Client } from "@aws-sdk/client-s3";

let _s3Client: S3Client | null = null;

/**
 * Get or create S3 client instance
 * Lazy initialization to allow environment variables to be loaded first
 */
function getS3Client(): S3Client {
  if (_s3Client) {
    return _s3Client;
  }

  // Validate required environment variables
  if (!process.env.AWS_BUCKET_NAME) {
    throw new Error("AWS_BUCKET_NAME environment variable is required");
  }

  if (!process.env.AWS_BUCKET_REGION) {
    throw new Error("AWS_BUCKET_REGION environment variable is required");
  }

  if (!process.env.AWS_PUBLIC_ACCESS_KEY) {
    throw new Error("AWS_ACCESS_KEY environment variable is required");
  }

  if (!process.env.AWS_SECRET_ACCESS_KEY) {
    throw new Error("AWS_SECRET_ACCESS_KEY environment variable is required");
  }

  _s3Client = new S3Client({
    region: process.env.AWS_BUCKET_REGION,
    credentials: {
      accessKeyId: process.env.AWS_PUBLIC_ACCESS_KEY,
      secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
    },
  });

  return _s3Client;
}

/**
 * S3 Client Configuration
 * Configured for eu-north-1 region with proper credentials
 */
export const s3Client = new Proxy({} as S3Client, {
  get(target, prop) {
    const client = getS3Client();
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    return (client as any)[prop];
  },
});

export function getS3BucketName(): string {
  if (!process.env.AWS_BUCKET_NAME) {
    throw new Error("AWS_BUCKET_NAME environment variable is required");
  }
  return process.env.AWS_BUCKET_NAME;
}

export function getS3Region(): string {
  if (!process.env.AWS_BUCKET_REGION) {
    throw new Error("AWS_BUCKET_REGION environment variable is required");
  }
  return process.env.AWS_BUCKET_REGION;
}

// For backward compatibility, export lazy getters
export const S3_BUCKET_NAME = process.env.AWS_BUCKET_NAME || "";
export const S3_REGION = process.env.AWS_BUCKET_REGION || "";
