import { NextRequest, NextResponse } from "next/server";
import {
  db,
  hashPassword,
  generateTemporaryPassword,
} from "@/lib/admin/db";
import { requireMainAdmin, getClientMetadata } from "@/lib/admin/auth";
import { sendMail } from "@/lib/mail";
import { renderEmail } from "@/emails/render";
import { AdminPasswordResetEmail } from "@/emails/templates/admin-password-reset";

export const dynamic = "force-dynamic";

export async function POST(
  req: NextRequest,
  context: { params: Promise<{ id: string }> }
) {
  try {
    const { user: mainAdmin } = await requireMainAdmin(req);
    const { ip } = getClientMetadata(req);
    const { id } = await context.params;

    const target = await db.getUserById(id);
    if (!target) {
      return NextResponse.json({ error: "Administrator not found." }, { status: 404 });
    }

    if (target.level === "MAIN_ADMIN") {
      return NextResponse.json(
        { error: "Main Administrator password cannot be reset via this endpoint. Use your profile settings." },
        { status: 400 }
      );
    }

    // Generate new temporary credentials
    const temporaryPassword = generateTemporaryPassword();
    const { hash, salt } = hashPassword(temporaryPassword);

    // Update user
    await db.updateUser(target.id, {
      passwordHash: hash,
      passwordSalt: salt,
      passwordChangeRequired: true,
    });

    // Invalidate all existing sessions
    await db.revokeAllSessionsForUser(
      target.id,
      mainAdmin.email,
      "Password reset by Main Administrator"
    );

    // If there were any pending reset requests for this user, mark them APPROVED
    const pendingReq = await db.getPendingResetRequestForUser(target.id);
    if (pendingReq) {
      await db.updateResetRequest(pendingReq.id, "APPROVED", mainAdmin.email, "Reset by Main Administrator");
    }

    // Security Audit logging (NEVER include passwords!)
    await db.logSecurityEvent({
      actorId: mainAdmin.id,
      actorName: mainAdmin.name,
      actorEmail: mainAdmin.email,
      actorLevel: mainAdmin.level,
      targetUserId: target.id,
      targetUserEmail: target.email,
      targetUserName: target.name,
      action: "PASSWORD_RESET_COMPLETED",
      details: {
        note: `Password reset by Main Admin ${mainAdmin.name}; sessions revoked; forced password change enabled`,
      },
      ipAddress: ip,
    });

    // Send branded password reset email
    let emailSent = false;
    try {
      const { html, text } = await renderEmail(
        AdminPasswordResetEmail({
          name: target.name,
          email: target.email,
          temporaryPassword,
        })
      );

      await sendMail({
        to: target.email,
        subject: "Your Quto AI Admin Password Has Been Reset",
        html,
        text,
      });
      emailSent = true;
    } catch (mailError) {
      console.error("[reset-password] Email delivery failure:", mailError);
    }

    return NextResponse.json({
      ok: true,
      temporaryPassword,
      emailSent,
      message: emailSent
        ? `Password has been reset. Login instructions sent to ${target.email}.`
        : `Password reset successfully, but the notification email could not be sent. Please share the key manually.`,
    });
  } catch (error) {
    const status = (error as unknown as { status: number }).status || 500;
    return NextResponse.json(
      { error: (error as Error).message || "Failed to reset administrator password." },
      { status }
    );
  }
}
