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

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