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);
    
    // Validate required fields
    if (!body.username || !body.password) {
      return {
        statusCode: 400,
        message: "Username and password are required"
      };
    }
    
    // Find user by username
    const user = await prisma.user.findFirst({
      where: {
        userUsername: body.username
      },
      include: {
        department: {
          select: {
            dp_id: true,
            dp_name: true,
            organization: {
              select: {
                org_id: true,
                org_name: true
              }
            }
          }
        },
        userrole: {
          select: {
            role: {
              select: {
                roleID: true,
                roleName: true
              }
            }
          }
        }
      }
    });
    
    if (!user) {
      return {
        statusCode: 404,
        message: "User not found"
      };
    }
    
    // Check if user is active
    if (user.userStatus !== "ACTIVE") {
      return {
        statusCode: 403,
        message: "User account is not active"
      };
    }
    
    // Verify password
    const hashedPassword = sha256(body.password).toString();
    if (user.userPassword !== hashedPassword) {
      return {
        statusCode: 401,
        message: "Invalid password"
      };
    }
    
    // Create audit log for successful login
    await prisma.audit.create({
      data: {
        auditIP: getRequestIP(event),
        auditURL: getRequestURL(event),
        auditURLMethod: 'POST',
        auditAction: 'USER_LOGIN',
        auditDetails: JSON.stringify({
          userID: user.userID,
          username: user.userUsername
        }),
        auditUserID: user.userID,
        auditUsername: user.userUsername
      }
    });
    
    // Extract roles for response
    const roles = user.userrole.map(ur => ur.role.roleName);
    
    // Prepare user data for response (remove sensitive information)
    const userData = {
      userID: user.userID,
      username: user.userUsername,
      fullName: user.userFullName,
      email: user.userEmail,
      phone: user.userPhone,
      department: user.department,
      roles: roles
    };
    
    return {
      statusCode: 200,
      message: "Login successful",
      data: userData
    };
  } catch (error) {
    console.error("Login error:", 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;
} 