import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3"; // ES Modules import
import { readMultipartFormData } from 'h3';

export default defineEventHandler(async (event) => {

    const parts = [];

    // Allow headers for specific origins
    // setHeader(event, 'Access-Control-Allow-Origin', 'http://localhost:3000');
    // setHeader(event, 'Access-Control-Allow-Methods', 'POST, OPTIONS');
    // setHeader(event, 'Access-Control-Allow-Headers', 'Content-Type');

    if (event.method === 'OPTIONS') {
        return new Response(null, { status: 204 });
    }

    try {
        const parts = await readMultipartFormData(event, { maxSize: 20 * 1024 * 1024});

        if (!parts) {
            return {
                status: 400,
                message: "Bad request. No parts found."
            }
        }
    } catch (error) {
        console.error('Failed to read multi-part data:', error);
        return {
            status: 500,
            message: "Failed to read multi-part data"
        }
    }

    console.log("Hello from the backend!");

    const S3_Config = {
        region: process.env.NUXT_AWS_REGION,
        credentials: {
            accessKeyId: process.env.NUXT_AWS_ACCESS_KEY_ID,
            secretAccessKey: process.env.NUXT_AWS_SECRET_ACCESS_KEY
        }
    }

    // Create S3 client with config
    const s3Client = new S3Client(S3_Config);

    // const { fileName, file } = await readMultipartFormData(event);

    const fileNamePart = parts.find(p => p.name === "fileName");
    const filePart = parts.find(p => p.name === "file");

    if (!fileNamePart || !filePart) {
        return {
            status: 400,
            message: "Missing required fields { fileName, file }"
        }
    }

    const fileName = fileNamePart.data.toString();
    const file = filePart.data;

    const input = {
        Bucket: process.env.NUXT_AWS_BUCKET,
        Key: fileName,
        Body: file,
        ContentType: filePart.type
    }

    const command = new PutObjectCommand(input);

    try {
        const response = await s3Client.send(command);
        console.log(response);
        return response;
    } catch (error) {
        console.error(error);
        return {
            status: 500,
            message: "Failed to upload file to S3",
            error: error
        }
    }
})