// app/api/frontend/upload/route.js
import { NextResponse } from 'next/server';
import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';
import { generateS3Key, getUploadPath } from '../../../../constants/uploadPath';
import { addImageToContent } from '../../../utils/imageContent';

const s3 = new S3Client({
  region: process.env.AWS_DEFAULT_REGION,
  credentials: {
    accessKeyId: process.env.AWS_ACCESS_KEY_ID,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
  },
  forcePathStyle: process.env.AWS_USE_PATH_STYLE_ENDPOINT === 'true',
});

export async function OPTIONS() {
  return NextResponse.json({}, { status: 200 });
}

export async function POST(req) {
  try {
    // Check API key
    const url = new URL(req.url);
    const apiKey = url.searchParams.get('api_key');
    
    if (apiKey !== process.env.APP_API_KEY && apiKey !== process.env.APP_API_KEY) {
      return NextResponse.json({ 
        success: false, 
        message: 'Invalid API key' 
      }, { status: 401 });
    }

    const formData = await req.formData();
    const file = formData.get('image');
    const uploadType = formData.get('uploadType') || 'general';

    if (!file) {
      return NextResponse.json({ 
        success: false, 
        message: 'No file uploaded' 
      }, { status: 400 });
    }

    console.log('File type:', typeof file);
    console.log('File constructor:', file.constructor?.name);
    console.log('File keys:', Object.keys(file));

    let fileBuffer;
    let fileName;
    let fileType;

    // Handle React Native's Blob or custom object
    if (file && typeof file === 'object') {
      // If it has a uri property (React Native)
      if ('uri' in file) {
        fileName = file.name || `upload_${Date.now()}.jpg`;
        fileType = file.type || 'image/jpeg';
        
        // Fetch the file from URI
        const response = await fetch(file.uri);
        const arrayBuffer = await response.arrayBuffer();
        fileBuffer = Buffer.from(arrayBuffer);
      }
      // If it's a Blob
      else if (file.arrayBuffer) {
        fileName = file.name || `upload_${Date.now()}.jpg`;
        fileType = file.type || 'image/jpeg';
        const arrayBuffer = await file.arrayBuffer();
        fileBuffer = Buffer.from(arrayBuffer);
      }
      // If it's already a Buffer or can be converted
      else if (file._data || file.data) {
        const data = file._data || file.data;
        if (Buffer.isBuffer(data)) {
          fileBuffer = data;
        } else if (typeof data === 'string') {
          fileBuffer = Buffer.from(data);
        }
        fileName = file.name || `upload_${Date.now()}.jpg`;
        fileType = file.type || 'image/jpeg';
      }
      else {
        // Try to convert the whole object
        console.log('Unknown object structure:', JSON.stringify(file, null, 2));
        return NextResponse.json({ 
          success: false, 
          message: 'Unable to process file: unknown structure',
          debug: { keys: Object.keys(file), constructor: file.constructor?.name }
        }, { status: 400 });
      }
    } 
    else {
      return NextResponse.json({ 
        success: false, 
        message: 'Invalid file format',
        debug: { type: typeof file }
      }, { status: 400 });
    }

    if (!fileBuffer) {
      return NextResponse.json({ 
        success: false, 
        message: 'Failed to extract file buffer' 
      }, { status: 400 });
    }

    console.log(`Processing upload: ${fileName}, type: ${fileType}, size: ${fileBuffer.length} bytes`);

    // Generate S3 key
    const s3Key = generateS3Key(uploadType, fileName);
    const uploadPath = getUploadPath(uploadType);
    const bucket = process.env.AWS_BUCKET;

    if (!bucket) {
      throw new Error('AWS bucket not configured');
    }

    const uploadParams = {
      Bucket: bucket,
      Key: s3Key,
      Body: fileBuffer,
      ContentType: fileType,
    };

    await s3.send(new PutObjectCommand(uploadParams));

    const fileUrl = `https://${bucket}.s3.${process.env.AWS_DEFAULT_REGION}.amazonaws.com/${s3Key}`;

    // Save image data
    const imageData = {
      filename: s3Key.split('/').pop(),
      originalName: fileName,
      s3Key: s3Key,
      s3Url: fileUrl,
      uploadType: uploadType,
      uploadPath: uploadPath,
      size: fileBuffer.length,
      mimeType: fileType
    };

    const savedImage = addImageToContent(imageData);

    return NextResponse.json({
      success: true,
      url: fileUrl,
      uploadType,
      uploadPath,
      s3Key,
      imageId: savedImage.id,
      message: `Image uploaded successfully to ${uploadPath}`
    });
    
  } catch (error) {
    console.error('Upload error:', error);
    return NextResponse.json(
      { success: false, message: 'Upload failed', error: error.message },
      { status: 500 }
    );
  }
}