import { S3Client, PutObjectCommand, GetObjectCommand } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import { logger } from './logger';

const region = process.env.AWS_REGION || 'ap-south-1';
const accessKeyId = process.env.AWS_ACCESS_KEY_ID || 'mock_access_key';
const secretAccessKey = process.env.AWS_SECRET_ACCESS_KEY || 'mock_secret_key';

export const s3BucketName = process.env.AWS_S3_BUCKET_NAME || 'indian-books-worldwide-bucket';

export const s3Client = new S3Client({
  region,
  credentials: {
    accessKeyId,
    secretAccessKey,
  },
});

export const getPresignedUploadUrl = async (
  fileKey: string,
  contentType: string,
  expiresInSeconds = 3600
): Promise<string> => {
  try {
    const command = new PutObjectCommand({
      Bucket: s3BucketName,
      Key: fileKey,
      ContentType: contentType,
    });
    return await getSignedUrl(s3Client, command, { expiresIn: expiresInSeconds });
  } catch (error) {
    logger.error(`Failed to generate S3 presigned upload URL: ${(error as Error).message}`);
    throw error;
  }
};

export const getPresignedDownloadUrl = async (
  fileKey: string,
  expiresInSeconds = 3600
): Promise<string> => {
  try {
    const command = new GetObjectCommand({
      Bucket: s3BucketName,
      Key: fileKey,
    });
    return await getSignedUrl(s3Client, command, { expiresIn: expiresInSeconds });
  } catch (error) {
    logger.error(`Failed to generate S3 presigned download URL: ${(error as Error).message}`);
    throw error;
  }
};
