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

export default defineEventHandler(async (event) => {
  try {
    // Get user ID from route
    const id = parseInt(event.context.params.id);
    
    if (isNaN(id)) {
      return {
        statusCode: 400,
        message: "Invalid user ID"
      };
    }
    
    // Get request body
    const body = await readBody(event);
    
    console.log("PUT User body:", JSON.stringify({
      ...body,
      userPassword: body.userPassword ? '[REDACTED]' : undefined
    }));
    
    // Validate request body
    if (!body || typeof body !== 'object') {
      return {
        statusCode: 400,
        message: "Invalid request body, expected JSON object",
        received: body
      };
    }
    
    // Check if user exists
    const existingUser = await prisma.user.findUnique({
      where: {
        userID: id
      }
    });
    
    if (!existingUser) {
      return {
        statusCode: 404,
        message: "User not found"
      };
    }
    
    // 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 is taken by another user
    if (body.userUsername && body.userUsername !== existingUser.userUsername) {
      const usernameExists = await prisma.user.findFirst({
        where: {
          userUsername: body.userUsername,
          userID: {
            not: id
          }
        }
      });
      
      if (usernameExists) {
        return {
          statusCode: 409,
          message: "Username is already taken by another user"
        };
      }
    }
    
    // Prepare update data
    const updateData = {};
    
    // Only update fields that are provided
    if (body.userUsername !== undefined) updateData.userUsername = body.userUsername;
    if (body.userFullName !== undefined) updateData.userFullName = body.userFullName;
    if (body.userEmail !== undefined) updateData.userEmail = body.userEmail;
    if (body.userPhone !== undefined) updateData.userPhone = body.userPhone;
    if (body.userStatus !== undefined) updateData.userStatus = body.userStatus ? body.userStatus.toUpperCase() : null;
    if (body.dp_id !== undefined) updateData.dp_id = body.dp_id ? parseInt(body.dp_id) : null;
    
    // Hash password if provided
    if (body.userPassword) {
      updateData.userPassword = sha256(body.userPassword).toString();
    }
    
    // Update modified date
    updateData.userModifiedDate = new Date();
    
    // Update user
    const user = await prisma.user.update({
      where: {
        userID: id
      },
      data: updateData
    });
    
    // Create audit log
    await prisma.audit.create({
      data: {
        auditIP: getRequestIP(event),
        auditURL: getRequestURL(event),
        auditURLMethod: 'PUT',
        auditAction: 'UPDATE_USER',
        auditDetails: JSON.stringify({
          before: {
            ...existingUser,
            userPassword: "[REDACTED]"
          },
          after: {
            ...user,
            userPassword: "[REDACTED]"
          }
        }),
        auditUserID: null,
        auditUsername: null
      }
    });
    
    // Remove password from response
    const userResponse = {
      ...user,
      userPassword: undefined
    };
    
    return {
      statusCode: 200,
      message: "User updated successfully",
      data: userResponse
    };
  } catch (error) {
    console.error("Error updating 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;
} 