import prisma from "../../utils/prisma";
import sha256 from "crypto-js/sha256";

export default defineEventHandler(async (event) => {
  try {
    // Get request body
    const body = await readBody(event);
    
    console.log("POST User 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.userUsername) {
      return {
        statusCode: 400,
        message: "Username is required",
        receivedBody: body
      };
    }
    
    if (!body.userPassword) {
      return {
        statusCode: 400,
        message: "Password is required",
        receivedBody: body
      };
    }
    
    if (!body.userFullName) {
      return {
        statusCode: 400,
        message: "Full name is required",
        receivedBody: body
      };
    }
    
    // Check if department exists if department ID is provided
    if (body.dp_id) {
      const department = await prisma.department.findUnique({
        where: {
          dp_id: parseInt(body.dp_id)
        }
      });
      
      if (!department) {
        return {
          statusCode: 404,
          message: "Department not found",
          dp_id: body.dp_id
        };
      }
    }
    
    // Check if username already exists
    const existingUser = await prisma.user.findFirst({
      where: {
        userUsername: body.userUsername
      }
    });
    
    if (existingUser) {
      return {
        statusCode: 409,
        message: "Username already exists"
      };
    }
    
    // Create random secret key
    const secretKey = generateRandomKey(32);
    
    // Encrypt password with SHA256
    const hashedPassword = sha256(body.userPassword).toString();
    
    // Create user
    const user = await prisma.user.create({
      data: {
        userSecretKey: secretKey,
        userUsername: body.userUsername,
        userPassword: hashedPassword,
        userFullName: body.userFullName,
        userEmail: body.userEmail || null,
        userPhone: body.userPhone || null,
        userStatus: body.userStatus ? body.userStatus.toUpperCase() : "ACTIVE",
        dp_id: body.dp_id ? parseInt(body.dp_id) : null,
        userCreatedDate: new Date(),
        userModifiedDate: new Date()
      }
    });
    
    // Create audit log
    await prisma.audit.create({
      data: {
        auditIP: getRequestIP(event),
        auditURL: getRequestURL(event),
        auditURLMethod: 'POST',
        auditAction: 'CREATE_USER',
        auditDetails: JSON.stringify({
          ...user,
          userPassword: "[REDACTED]" // Redact password in audit log
        }),
        auditUserID: null,
        auditUsername: null
      }
    });
    
    // Remove password from response
    const userResponse = {
      ...user,
      userPassword: undefined
    };
    
    return {
      statusCode: 201,
      message: "User created successfully",
      data: userResponse
    };
  } catch (error) {
    console.error("Error creating user:", 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;
}

function generateRandomKey(length) {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let result = '';
  for (let i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return result;
} 