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

export default defineEventHandler(async (event) => {
  try {
    // Get request body
    const body = await readBody(event);
    
    console.log("POST Request 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.org_name) {
      return {
        statusCode: 400,
        message: "Organization name is required",
        receivedBody: body
      };
    }
    
    // Check if organization already exists
    const existingOrg = await prisma.organization.findUnique({
      where: {
        org_name: body.org_name
      }
    });
    
    if (existingOrg) {
      return {
        statusCode: 409,
        message: "Organization with this name already exists"
      };
    }
    
    // Create organization
    const organization = await prisma.organization.create({
      data: {
        org_name: body.org_name,
        org_address1: body.org_address1 || null,
        org_address2: body.org_address2 || null,
        org_postcode: body.org_postcode ? parseInt(body.org_postcode) : null,
        org_state: body.org_state || null,
        org_country: body.org_country || null,
        org_active: body.org_active !== undefined ? parseInt(body.org_active) : 1
      }
    });
    
    // Create audit log
    await prisma.audit.create({
      data: {
        auditIP: getRequestIP(event),
        auditURL: getRequestURL(event),
        auditURLMethod: 'POST',
        auditAction: 'CREATE_ORGANIZATION',
        auditDetails: JSON.stringify(organization),
        auditUserID: null,
        auditUsername: null
      }
    });
    
    return {
      statusCode: 201,
      message: "Organization created successfully",
      data: organization
    };
  } catch (error) {
    console.error("Error creating 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;
} 