import { randomBytes } from "crypto";
import { EncryptionService } from "../services/encryption/encryption.service";

const axios = require("axios");
const path = require("path");
import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';
export async function uploadFileToS3(imageUrl, filePath, s3Config) {
  try {

    const s3 = new S3Client({
      region: process.env.AWS_DEFAULT_REGION,
      credentials: {
        accessKeyId: s3Config.accessKeyId,
        secretAccessKey: s3Config.secretAccessKey,
      },
    });
    // Download image from URL
    const response = await axios.get(imageUrl, { responseType: "arraybuffer" });
    let fileName = path.basename(new URL(imageUrl).pathname);
    const contentType = response.headers['content-type'] || "image/jpeg";
    const randomStr = randomBytes(3).toString("hex");
    fileName = `${randomStr}-${fileName}`
    // Upload to S3
    const bucketName = process.env.AWS_BUCKET;
    filePath = `${filePath}/${fileName}`
    const uploadParams = {
      Bucket: bucketName,
      Key: filePath,
      Body: Buffer.from(response.data),
      ContentType: contentType,
    };

    await s3.send(new PutObjectCommand(uploadParams));
    return {
      fileName,
      path: `${process.env.AWS_FILE_PATH}${filePath}`
    }

  } catch (error) {
    console.error("Error downloading or uploading the image:", error?.response?.data?.errors || error.message);
    return null;
  }
}
