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

export default defineEventHandler(async (event) => {
  try {
    // Get department ID from route
    const id = parseInt(event.context.params.id);
    
    if (isNaN(id)) {
      return {
        statusCode: 400,
        message: "Invalid department ID"
      };
    }
    
    // Check if department exists and get related entities
    const existingDept = await prisma.department.findUnique({
      where: {
        dp_id: id
      },
      include: {
        cabinets: {
          select: {
            cb_id: true
          }
        },
        users: {
          select: {
            su_id: true
          }
        }
      }
    });
    
    if (!existingDept) {
      return {
        statusCode: 404,
        message: "Department not found"
      };
    }
    
    // Check if department has related cabinets
    if (existingDept.cabinets.length > 0) {
      return {
        statusCode: 409,
        message: "Cannot delete department with existing cabinets. Remove all cabinets first.",
        cabinetCount: existingDept.cabinets.length
      };
    }
    
    // Check if department has related users
    if (existingDept.users.length > 0) {
      return {
        statusCode: 409,
        message: "Cannot delete department with existing users. Reassign or remove all users first.",
        userCount: existingDept.users.length
      };
    }
    
    // Delete department
    const department = await prisma.department.delete({
      where: {
        dp_id: id
      }
    });
    
    // Create audit log
    await prisma.audit.create({
      data: {
        auditIP: getRequestIP(event),
        auditURL: getRequestURL(event),
        auditURLMethod: 'DELETE',
        auditAction: 'DELETE_DEPARTMENT',
        auditDetails: JSON.stringify(existingDept),
        auditUserID: null,
        auditUsername: null
      }
    });
    
    return {
      statusCode: 200,
      message: "Department deleted successfully"
    };
  } catch (error) {
    console.error("Error deleting department:", 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;
} 