import { requireAuth } from '~/server/utils/auth';
import { getMinioClient } from '~/server/utils/minio';
import mime from 'mime-types';

export default defineEventHandler(async (event) => {
  // Check authentication (x-tag header OR Keycloak session)
  await requireAuth(event);
  
  try {
    const query = getQuery(event);
    const fileName = query.fileName as string;
    const bucket = (query.bucket as string) || 'client-portal'; // Support bucket parameter
    
    console.log('Proxy preview requested for:', fileName, 'in bucket:', bucket);
    
    if (!fileName) {
      throw createError({
        statusCode: 400,
        statusMessage: 'File name is required',
      });
    }
    
    // Get content type
    const contentType = mime.lookup(fileName) || 'application/octet-stream';
    console.log('Content type:', contentType);
    
    // Get the download URL with the correct bucket
    const client = getMinioClient();
    const url = await client.presignedGetObject(bucket, fileName, 60 * 60);
    console.log('MinIO URL obtained for bucket:', bucket);
    
    // Fetch the file content from MinIO
    const response = await fetch(url);
    console.log('MinIO response status:', response.status);
    
    if (!response.ok) {
      throw createError({
        statusCode: response.status,
        statusMessage: 'Failed to fetch file from storage',
      });
    }
    
    // Get the file data as ArrayBuffer
    const arrayBuffer = await response.arrayBuffer();
    const buffer = Buffer.from(arrayBuffer);
    
    console.log('File size:', buffer.length, 'bytes');
    
    // Set appropriate headers for preview
    setHeader(event, 'Content-Type', contentType);
    setHeader(event, 'Content-Disposition', `inline; filename="${fileName.split('/').pop()}"`);
    setHeader(event, 'Cache-Control', 'public, max-age=3600');
    setHeader(event, 'Content-Length', buffer.length);
    
    // For PDF files, add additional headers
    if (contentType === 'application/pdf') {
      setHeader(event, 'X-Content-Type-Options', 'nosniff');
    }
    
    console.log('Returning buffer for preview');
    
    // Return the buffer directly - Nitro will handle it properly
    return buffer;
  } catch (error: any) {
    console.error('Failed to proxy preview:', error);
    throw createError({
      statusCode: 500,
      statusMessage: error.message || 'Failed to proxy preview',
    });
  }
});
