/**
 * Change Password API
 * Allows staff to change their own password
 * Allows super admin to change any user's password
 */

import { NextRequest, NextResponse } from "next/server";
import { getStaffSession } from "@/lib/staff-session";
import { prisma } from "@/lib/db";
import { logger } from "@/lib/logger";
import bcrypt from "bcryptjs";
import validator from "validator";

export async function POST(request: NextRequest) {
  try {
    const currentUser = await getStaffSession();

    if (!currentUser) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const body = await request.json();
    const { userId, currentPassword, newPassword } = body;

    // Validate new password
    if (!newPassword || newPassword.length < 12) {
      return NextResponse.json(
        { error: "Password must be at least 12 characters" },
        { status: 400 },
      );
    }

    // Check password strength
    if (
      !validator.isStrongPassword(newPassword, {
        minLength: 12,
        minLowercase: 1,
        minUppercase: 1,
        minNumbers: 1,
        minSymbols: 0, // Don't require symbols
      })
    ) {
      return NextResponse.json(
        { error: "Password must contain uppercase, lowercase, and numbers" },
        { status: 400 },
      );
    }

    let targetUserId = userId;
    let targetUser;

    // If changing another user's password (super admin only)
    if (userId && userId !== currentUser.id) {
      // Only super admin can change other users' passwords
      if (currentUser.role !== "SUPER_ADMIN") {
        return NextResponse.json(
          { error: "Only super admins can change other users passwords" },
          { status: 403 },
        );
      }

      targetUser = await prisma.users.findUnique({
        where: { id: userId },
      });

      if (!targetUser) {
        return NextResponse.json({ error: "User not found" }, { status: 404 });
      }

      targetUserId = userId;
    } else {
      // Changing own password - verify current password
      if (!currentPassword) {
        return NextResponse.json(
          { error: "Current password required" },
          { status: 400 },
        );
      }

      targetUser = await prisma.users.findUnique({
        where: { id: currentUser.id },
      });

      if (!targetUser || !targetUser.password) {
        return NextResponse.json({ error: "User not found" }, { status: 404 });
      }

      // Verify current password
      const isValid = await bcrypt.compare(
        currentPassword,
        targetUser.password,
      );
      if (!isValid) {
        return NextResponse.json(
          { error: "Current password is incorrect" },
          { status: 401 },
        );
      }

      targetUserId = currentUser.id;
    }

    // Ensure targetUserId is valid before proceeding
    if (!targetUserId) {
      logger.error("[Password Change] targetUserId is undefined/null");
      return NextResponse.json({ error: "Invalid user ID" }, { status: 400 });
    }

    // Hash new password
    const hashedPassword = await bcrypt.hash(newPassword, 12);

    // Update password in database
    const updatedUser = await prisma.users.update({
      where: { id: targetUserId },
      data: {
        password: hashedPassword,
        updatedAt: new Date(),
      },
    });

    // Log password change

    return NextResponse.json({
      success: true,
      message: "Password updated successfully",
    });
  } catch (error) {
    logger.error("Password change error", error);
    return NextResponse.json(
      { error: "Failed to change password" },
      { status: 500 },
    );
  }
}
