import { readMultipartFormData } from 'h3';
import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";

export default defineEventHandler(async (event) => {
    const s3 = new S3Client({
        region: 'ap-southeast-1',
        credentials: {
            accessKeyId: process.env.NUXT_AWS_ACCESS_KEY_ID,
            secretAccessKey: process.env.NUXT_AWS_SECRET_ACCESS_KEY,
        }
    });

    try {
        const parts = await readMultipartFormData(event, { maxSize: 1024 * 1024 }); // 1MB limit since we're only handling metadata
        
        if (!parts) {
            return {
                status: 400,
                message: "No form data received"
            };
        }

        // Extract form data
        const name = parts.find(p => p.name === 'name')?.data.toString() || '';
        const animal = parts.find(p => p.name === 'animal')?.data.toString() || '';
        const fileName = parts.find(p => p.name === 'fileName')?.data.toString();
        const fileType = parts.find(p => p.name === 'fileType')?.data.toString();

        // Log the received data
        console.log('Received name:', name);
        console.log('Received favorite animal:', animal);
        
        // Prepare response message
        let message = `You are ${name} and your favorite animal is ${animal}`;
        
        let signedUrl = null;
        if (fileName && fileType) {
            console.log('Received file metadata:', { fileName, fileType });
            message += `. You will upload the file: ${fileName}`;
            
            // Generate a unique key using timestamp and filename
            const uploadKey = `uploads/${Date.now()}-${fileName}`;

            const s3Command = new PutObjectCommand({
                Bucket: process.env.NUXT_AWS_BUCKET,
                Key: uploadKey,
                ContentType: fileType,
            });

            signedUrl = await getSignedUrl(s3, s3Command, { expiresIn: 60 });
        }

        return {
            status: 200,
            message,
            signedUrl
        };
    } catch (error) {
        console.error("Error processing request:", error);
        return {
            status: 500,
            message: "Error processing request",
            error: error.message
        };
    }
});