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

export default defineEventHandler(async (event) => {
  try {
    // Get request body
    const body = await readBody(event);
    
    console.log("POST 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
      };
    }
    
    // Validate required fields
    if (!body.dp_name) {
      return {
        statusCode: 400,
        message: "Department name is required",
        receivedBody: body
      };
    }
    
    if (!body.org_id) {
      return {
        statusCode: 400,
        message: "Organization ID (org_id) is required",
        receivedBody: body
      };
    }
    
    // Check if organization exists
    const organization = await prisma.organization.findUnique({
      where: {
        org_id: parseInt(body.org_id)
      }
    });
    
    if (!organization) {
      return {
        statusCode: 404,
        message: "Organization not found",
        org_id: body.org_id
      };
    }
    
    // Create department
    const department = await prisma.department.create({
      data: {
        dp_name: body.dp_name,
        org_id: parseInt(body.org_id)
      }
    });
    
    // Create audit log
    await prisma.audit.create({
      data: {
        auditIP: getRequestIP(event),
        auditURL: getRequestURL(event),
        auditURLMethod: 'POST',
        auditAction: 'CREATE_DEPARTMENT',
        auditDetails: JSON.stringify(department),
        auditUserID: null,
        auditUsername: null
      }
    });
    
    return {
      statusCode: 201,
      message: "Department created successfully",
      data: department
    };
  } catch (error) {
    console.error("Error creating 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;
} 