import { S3 } from 'aws-sdk';

const s3 = new S3({
  accessKeyId: process.env.NEXT_PUBLIC_AWS_ACCESS_KEY_ID,
  secretAccessKey: process.env.NEXT_PUBLIC_AWS_SECRET_ACCESS_KEY,
  region: process.env.NEXT_PUBLIC_AWS_REGION,
});

export const uploadFile = async (file: File, onProgress: (progress: number) => void): Promise<string> => {
  const params = {
    Bucket: process.env.NEXT_PUBLIC_AWS_BUCKET_NAME!,
    Key: `uploads/${Date.now()}-${file.name}`,
    Body: file,
    ContentType: file.type,
  };

  return new Promise((resolve, reject) => {
    s3.upload(params)
      .on('httpUploadProgress', (evt) => {
        const progress = Math.round((evt.loaded / evt.total) * 100);
        onProgress(progress);
      })
      .send((err, data) => {
        if (err) reject(err);
        else resolve(data.Location);
      });
  });
};