import { NextRequest, NextResponse } from 'next/server';
import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';
import { v4 as uuidv4 } from 'uuid';

// Configure S3 client
const s3 = new S3Client({
  region: process.env.AWS_DEFAULT_REGION || 'us-east-1',
  credentials: {
    accessKeyId: process.env.AWS_ACCESS_KEY_ID!,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!,
  },
  forcePathStyle: process.env.AWS_USE_PATH_STYLE_ENDPOINT === 'true',
});

// Allowed MIME types for resumes
const ALLOWED_MIME_TYPES = [
  'application/pdf',
  'application/msword',
  'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  'text/plain'
];

// Allowed file extensions
const ALLOWED_EXTENSIONS = ['.pdf', '.doc', '.docx', '.txt'];

// Maximum file size (5MB)
const MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB in bytes

// Generate S3 key for resume
function generateResumeS3Key(originalFilename: string): string {
  const timestamp = Date.now();
  const uniqueId = uuidv4().split('-')[0]; // Use first part of UUID for shorter ID
  const extension = originalFilename.includes('.') 
    ? originalFilename.split('.').pop() 
    : 'pdf';
  
  // Sanitize filename
  const sanitizedFilename = originalFilename
    .replace(/\.[^/.]+$/, '') // Remove existing extension
    .replace(/[^a-zA-Z0-9_-]/g, '_') // Replace special characters
    .substring(0, 50); // Limit length
  
  return `resumes/${timestamp}-${uniqueId}-${sanitizedFilename}.${extension}`;
}

// Validate file
function validateFile(file: File): { isValid: boolean; error?: string } {
  // Check file size
  if (file.size > MAX_FILE_SIZE) {
    return { 
      isValid: false, 
      error: `File size exceeds ${MAX_FILE_SIZE / (1024 * 1024)}MB limit` 
    };
  }

  // Check MIME type
  if (!ALLOWED_MIME_TYPES.includes(file.type)) {
    return { 
      isValid: false, 
      error: `Invalid file type. Allowed types: ${ALLOWED_EXTENSIONS.join(', ')}` 
    };
  }

  // Check file extension
  const fileExtension = '.' + file.name.split('.').pop()?.toLowerCase();
  if (!ALLOWED_EXTENSIONS.includes(fileExtension)) {
    return { 
      isValid: false, 
      error: `Invalid file extension. Allowed: ${ALLOWED_EXTENSIONS.join(', ')}` 
    };
  }

  return { isValid: true };
}

export async function POST(req: NextRequest) {
  try {
    // Parse form data
    const formData = await req.formData();
    const file = formData.get('resume') as File;
    const candidateName = formData.get('candidateName') as string;
    const candidateEmail = formData.get('candidateEmail') as string;

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

    // Validate file
    const validation = validateFile(file);
    if (!validation.isValid) {
      return NextResponse.json(
        { success: false, message: validation.error },
        { status: 400 }
      );
    }

    // Generate unique S3 key
    const s3Key = generateResumeS3Key(file.name);
    
    // Convert file to buffer
    const buffer = Buffer.from(await file.arrayBuffer());
    
    // Prepare S3 upload parameters
    const uploadParams = {
      Bucket: process.env.AWS_BUCKET!,
      Key: s3Key,
      Body: buffer,
      ContentType: file.type,
      ContentDisposition: `attachment; filename="${file.name}"`,
      Metadata: {
        'original-filename': file.name,
        'candidate-name': candidateName || 'unknown',
        'candidate-email': candidateEmail || 'unknown',
        'upload-timestamp': Date.now().toString(),
      },
    };

    // Upload to S3
    await s3.send(new PutObjectCommand(uploadParams));

    // Generate public URL (assuming bucket is public or has proper permissions)
    const url = `https://${process.env.AWS_BUCKET}.s3.${process.env.AWS_DEFAULT_REGION}.amazonaws.com/${s3Key}`;

    // Optional: Store metadata in database (you can add your database logic here)
    const resumeData = {
      id: uuidv4(),
      originalName: file.name,
      s3Key,
      s3Url: url,
      size: file.size,
      mimeType: file.type,
      candidateName,
      candidateEmail,
      uploadDate: new Date().toISOString(),
    };

    // You can save resumeData to your database here
    // Example: await prisma.resume.create({ data: resumeData });

    return NextResponse.json({
      success: true,
      message: 'Resume uploaded successfully',
      data: {
        url,
        filename: file.name,
        originalName: file.name,
        s3Key,
        size: file.size,
        mimeType: file.type,
        uploadDate: new Date().toISOString(),
      },
    });

  } catch (error: any) {
    console.error('Resume upload error:', error);
    
    return NextResponse.json(
      { 
        success: false, 
        message: 'Resume upload failed', 
        error: error.message || 'Unknown error occurred' 
      },
      { status: 500 }
    );
  }
}

// Add CORS headers for cross-origin requests
export async function OPTIONS(req: NextRequest) {
  return NextResponse.json(
    {},
    {
      status: 200,
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'POST, OPTIONS',
        'Access-Control-Allow-Headers': 'Content-Type',
      },
    }
  );
}

// Optional: Add a GET endpoint to list resumes (if needed)
export async function GET(req: NextRequest) {
  return NextResponse.json(
    { success: true, message: 'Resume upload endpoint is active' },
    { status: 200 }
  );
}