import { deleteFile, deleteFolder } from '~/server/utils/minio';

export default defineEventHandler(async (event) => {
  try {
    const body = await readBody(event);
    const { fileName, isFolder } = body;
    
    if (!fileName) {
      throw createError({
        statusCode: 400,
        statusMessage: 'File name is required',
      });
    }
    
    // Delete folder or file based on type
    if (isFolder) {
      await deleteFolder(fileName);
    } else {
      await deleteFile(fileName);
    }
    
    // Log audit event
    await logAuditEvent(event, 'delete', fileName);
    
    return {
      success: true,
      message: isFolder ? 'Folder deleted successfully' : 'File deleted successfully',
    };
  } catch (error: any) {
    console.error('Failed to delete:', error);
    throw createError({
      statusCode: 500,
      statusMessage: error.message || 'Failed to delete',
    });
  }
});

// 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';
}
