import prisma from "../../utils/prisma";

export default defineEventHandler(async (event) => {
  try {
    // Get user ID from route
    const id = parseInt(event.context.params.id);
    
    if (isNaN(id)) {
      return {
        statusCode: 400,
        message: "Invalid user ID"
      };
    }
    
    // Check if user exists
    const existingUser = await prisma.user.findUnique({
      where: {
        userID: id
      },
      include: {
        userrole: {
          select: {
            userRoleID: true
          }
        }
      }
    });
    
    if (!existingUser) {
      return {
        statusCode: 404,
        message: "User not found"
      };
    }
    
    // Check if user has any roles assigned
    if (existingUser.userrole && existingUser.userrole.length > 0) {
      // Delete all associated user roles first
      await prisma.userrole.deleteMany({
        where: {
          userRoleUserID: id
        }
      });
    }
    
    // Create a sanitized copy of user data for audit log
    const sanitizedUser = {
      ...existingUser,
      userPassword: "[REDACTED]",
      userSecretKey: "[REDACTED]"
    };
    
    // Delete user
    await prisma.user.delete({
      where: {
        userID: id
      }
    });
    
    // Create audit log
    await prisma.audit.create({
      data: {
        auditIP: getRequestIP(event),
        auditURL: getRequestURL(event),
        auditURLMethod: 'DELETE',
        auditAction: 'DELETE_USER',
        auditDetails: JSON.stringify(sanitizedUser),
        auditUserID: null,
        auditUsername: null
      }
    });
    
    return {
      statusCode: 200,
      message: "User deleted successfully"
    };
  } catch (error) {
    console.error("Error deleting user:", error);
    
    return {
      statusCode: 500,
      message: "Internal server error",
      error: error.message
    };
  }
});

// Helper functions
function getRequestIP(event) {
  return event.node.req.headers['x-forwarded-for'] || 
         event.node.req.connection.remoteAddress;
}

function getRequestURL(event) {
  return event.node.req.url;
} 