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

export default defineEventHandler(async (event) => {
  // Check authentication (x-tag header OR Keycloak session)
  await requireAuth(event);
  
  try {
    const body = await readBody(event);
    const { folderPath } = body;
    
    if (!folderPath) {
      throw createError({
        statusCode: 400,
        statusMessage: 'Folder path is required',
      });
    }
    
    // Create the folder
    await createFolder(folderPath);
    
    // Log audit event
    await logAuditEvent(event, 'create_folder', folderPath);
    
    return {
      success: true,
      message: 'Folder created successfully',
      folderPath,
    };
  } catch (error: any) {
    console.error('Failed to create folder:', error);
    throw createError({
      statusCode: 500,
      statusMessage: error.message || 'Failed to create folder',
    });
  }
});

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