import { S3Client, GetObjectCommand, DeleteObjectCommand } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import { Upload } from '@aws-sdk/lib-storage';

export const S3_BUCKET = process.env.S3_BUCKET || 'mam';

const s3Client = new S3Client({
  region: process.env.S3_REGION || 'us-east-1',
  endpoint: process.env.S3_ENDPOINT,
  credentials: {
    accessKeyId: process.env.S3_ACCESS_KEY,
    secretAccessKey: process.env.S3_SECRET_KEY,
  },
  forcePathStyle: true,
  requestChecksumCalculation: "WHEN_REQUIRED",
  responseChecksumValidation: "WHEN_REQUIRED",
});

export { s3Client };

export const getSignedUrlForObject = async (key, expiresIn = 3600, contentType = null) => {
  try {
    const params = { Bucket: S3_BUCKET, Key: key };
    if (contentType) params.ResponseContentType = contentType;
    const command = new GetObjectCommand(params);
    const url = await getSignedUrl(s3Client, command, { expiresIn });
    return url;
  } catch (err) {
    console.error('Error generating signed URL:', err);
    throw err;
  }
};

export const uploadStream = async (key, stream, contentType) => {
  try {
    const upload = new Upload({
      client: s3Client,
      params: {
        Bucket: S3_BUCKET,
        Key: key,
        Body: stream,
        ContentType: contentType,
      },
    });

    const result = await upload.done();
    return result;
  } catch (err) {
    console.error('Error uploading to S3:', err);
    throw err;
  }
};

export const deleteObject = async (key) => {
  try {
    const command = new DeleteObjectCommand({
      Bucket: S3_BUCKET,
      Key: key,
    });
    const result = await s3Client.send(command);
    return result;
  } catch (err) {
    console.error('Error deleting from S3:', err);
    throw err;
  }
};
