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"
      };
    }
    
    // Get request body
    const body = await readBody(event);
    
    console.log("Request body:", JSON.stringify(body));
    
    // Validate required fields
    if (!body || typeof body !== 'object') {
      return {
        statusCode: 400,
        message: "Invalid request body, expected JSON object",
        received: body
      };
    }
    
    if (!body.org_name) {
      return {
        statusCode: 400,
        message: "Organization name is required",
        receivedBody: body
      };
    }
    
    // Check if organization exists
    const existingOrg = await prisma.organization.findUnique({
      where: {
        org_id: id
      }
    });
    
    if (!existingOrg) {
      return {
        statusCode: 404,
        message: "Organization not found"
      };
    }
    
    // Check if the name is already taken by another organization
    if (body.org_name !== existingOrg.org_name) {
      const nameExists = await prisma.organization.findFirst({
        where: {
          org_name: body.org_name,
          org_id: {
            not: id
          }
        }
      });
      
      if (nameExists) {
        return {
          statusCode: 409,
          message: "Organization with this name already exists"
        };
      }
    }
    
    // Update organization
    const organization = await prisma.organization.update({
      where: {
        org_id: id
      },
      data: {
        org_name: body.org_name,
        org_address1: body.org_address1 !== undefined ? body.org_address1 : existingOrg.org_address1,
        org_address2: body.org_address2 !== undefined ? body.org_address2 : existingOrg.org_address2,
        org_postcode: body.org_postcode !== undefined ? parseInt(body.org_postcode) : existingOrg.org_postcode,
        org_state: body.org_state !== undefined ? body.org_state : existingOrg.org_state,
        org_country: body.org_country !== undefined ? body.org_country : existingOrg.org_country,
        org_active: body.org_active !== undefined ? parseInt(body.org_active) : existingOrg.org_active
      }
    });
    
    // Create audit log
    await prisma.audit.create({
      data: {
        auditIP: getRequestIP(event),
        auditURL: getRequestURL(event),
        auditURLMethod: 'PUT',
        auditAction: 'UPDATE_ORGANIZATION',
        auditDetails: JSON.stringify({
          before: existingOrg,
          after: organization
        }),
        auditUserID: null,
        auditUsername: null
      }
    });
    
    return {
      statusCode: 200,
      message: "Organization updated successfully",
      data: organization
    };
  } catch (error) {
    console.error("Error updating 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;
} 