import { requireAuth } from '~/server/utils/auth';
import { getDownloadUrl } from '~/server/utils/minio';

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;
    
    if (!fileName) {
      throw createError({
        statusCode: 400,
        statusMessage: 'File name is required',
      });
    }
    
    // Generate presigned URL valid for 1 hour
    const url = await getDownloadUrl(fileName);
    
    // Log audit event
    await logAuditEvent(event, 'download', fileName);
    
    return {
      success: true,
      url,
      fileName,
    };
  } catch (error: any) {
    console.error('Failed to generate download URL:', error);
    throw createError({
      statusCode: 500,
      statusMessage: error.message || 'Failed to generate download URL',
    });
  }
});

// Audit logging helper
async function logAuditEvent(event: any, action: string, filePath: string) {
  try {
    const user = event.context.user || { email: 'anonymous' };
    const auditLog = {
      user_email: user.email,
      action,
      file_path: filePath,
      timestamp: new Date().toISOString(),
      ip_address: getClientIP(event),
      success: true,
    };
    
    // You can store this in your database or logging system
    console.log('Audit log:', auditLog);
  } catch (error) {
    console.error('Failed to log audit event:', error);
  }
}

function getClientIP(event: any): string {
  return event.node.req.headers['x-forwarded-for'] || 
         event.node.req.connection.remoteAddress || 
         'unknown';
}
