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"
      };
    }
    
    // Get request body
    const body = await readBody(event);
    
    console.log("PUT Department body:", JSON.stringify(body));
    
    // Validate request body
    if (!body || typeof body !== 'object') {
      return {
        statusCode: 400,
        message: "Invalid request body, expected JSON object",
        received: body
      };
    }
    
    // Check if department exists
    const existingDept = await prisma.department.findUnique({
      where: {
        dp_id: id
      }
    });
    
    if (!existingDept) {
      return {
        statusCode: 404,
        message: "Department not found"
      };
    }
    
    // Validate required fields
    if (!body.dp_name) {
      return {
        statusCode: 400,
        message: "Department name is required",
        receivedBody: body
      };
    }
    
    // If org_id is provided, check if organization exists
    if (body.org_id !== undefined) {
      const orgId = parseInt(body.org_id);
      
      if (isNaN(orgId)) {
        return {
          statusCode: 400,
          message: "Invalid organization ID format"
        };
      }
      
      const organization = await prisma.organization.findUnique({
        where: {
          org_id: orgId
        }
      });
      
      if (!organization) {
        return {
          statusCode: 404,
          message: "Organization not found",
          org_id: body.org_id
        };
      }
    }
    
    // Update department
    const department = await prisma.department.update({
      where: {
        dp_id: id
      },
      data: {
        dp_name: body.dp_name,
        org_id: body.org_id !== undefined ? parseInt(body.org_id) : existingDept.org_id
      }
    });
    
    // Create audit log
    await prisma.audit.create({
      data: {
        auditIP: getRequestIP(event),
        auditURL: getRequestURL(event),
        auditURLMethod: 'PUT',
        auditAction: 'UPDATE_DEPARTMENT',
        auditDetails: JSON.stringify({
          before: existingDept,
          after: department
        }),
        auditUserID: null,
        auditUsername: null
      }
    });
    
    return {
      statusCode: 200,
      message: "Department updated successfully",
      data: department
    };
  } catch (error) {
    console.error("Error updating 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;
} 