// app/api/frontend/download-document/route.ts
import { NextRequest, NextResponse } from 'next/server';
import pool from '../../../../lib/db/db';
import { RowDataPacket } from 'mysql2';

export async function POST(req: NextRequest) {
  const comingHeaders = req.headers.get("authorization");

  if (comingHeaders !== process.env.APP_API_KEY) {
    return NextResponse.json(
      { success: false, message: 'Unauthorized Access' },
      { status: 401 }
    );
  }

  const connection = await pool.getConnection();

  try {
    const body = await req.json();
    const { documentId, downloadId } = body;

    console.log('📥 Download request:', { documentId, downloadId });

    if (!documentId) {
      return NextResponse.json(
        { success: false, message: 'Missing document ID' },
        { status: 400 }
      );
    }

    // Get the document file path from database
    const [documents] = await connection.execute<RowDataPacket[]>(
      `SELECT document_file, file_name FROM student_support_documents WHERE id = ?`,
      [documentId]
    );

    if (documents.length === 0) {
      return NextResponse.json(
        { success: false, message: 'Document not found' },
        { status: 404 }
      );
    }

    const document = documents[0];
    const s3Path = document.document_file;
    const fileName = document.file_name || `document_${documentId}`;
    
    // Construct the S3 URL
    const AWS_BUCKET = process.env.AWS_BUCKET || 'unipage-website';
    const AWS_REGION = process.env.AWS_DEFAULT_REGION || 'eu-north-1';
    const s3Url = `https://${AWS_BUCKET}.s3.${AWS_REGION}.amazonaws.com/${s3Path}`;

    console.log('📥 Fetching from S3:', s3Url);

    // Fetch the file from S3
    const response = await fetch(s3Url, {
      headers: {
        'User-Agent': 'Mozilla/5.0 (compatible; YourApp/1.0)',
      },
    });
    
    if (!response.ok) {
      console.error('S3 fetch error:', response.status, response.statusText);
      return NextResponse.json(
        { 
          success: false, 
          message: `Failed to fetch file from storage: ${response.status}`,
          status: response.status 
        },
        { status: response.status }
      );
    }

    // Get the file as a buffer
    const fileBuffer = await response.arrayBuffer();
    console.log('📥 File size:', fileBuffer.byteLength, 'bytes');
    
    // Determine content type
    const contentType = getContentType(fileName);
    
    // Return the file directly
    return new NextResponse(fileBuffer, {
      headers: {
        'Content-Type': contentType,
        'Content-Disposition': `attachment; filename="${fileName}"`,
        'Content-Length': fileBuffer.byteLength.toString(),
        'Cache-Control': 'no-cache, no-store, must-revalidate',
      },
    });

  } catch (error: any) {
    console.error('Download error:', error);
    return NextResponse.json(
      { 
        success: false, 
        message: 'Failed to download file', 
        error: error.message 
      },
      { status: 500 }
    );
  } finally {
    connection.release();
  }
}

function getContentType(fileName: string): string {
  const ext = fileName.split('.').pop()?.toLowerCase();
  switch (ext) {
    case 'pdf': return 'application/pdf';
    case 'png': return 'image/png';
    case 'jpg':
    case 'jpeg': return 'image/jpeg';
    case 'doc': return 'application/msword';
    case 'docx': return 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
    default: return 'application/octet-stream';
  }
}