import { NextResponse } from "next/server";

import { sendPasswordResetEmail } from "@/features/auth/lib/auth-emails";
import { buildPasswordResetUrl, issuePasswordResetToken } from "@/features/auth/lib/password-reset";
import { createAuditTrailSafe } from "@/lib/audit-trail";
import { requireApiAccess } from "@/lib/authorization";
import { prisma } from "@/lib/prisma";

type RouteContext = { params: Promise<{ id: string }> };

function parseBigInt(value: string) {
  try {
    return BigInt(value);
  } catch {
    return null;
  }
}

export async function POST(request: Request, context: RouteContext) {
  const auth = requireApiAccess(request);
  if (!auth.ok) return auth.response;

  const id = parseBigInt((await context.params).id);
  if (id === null) {
    return NextResponse.json({ message: "Invalid id" }, { status: 400 });
  }

  const user = await prisma.user.findUnique({ where: { id } });
  if (!user?.email) {
    return NextResponse.json({ message: "User tidak memiliki email aktif" }, { status: 404 });
  }

  const { plainToken } = await issuePasswordResetToken(user.id);
  await sendPasswordResetEmail({
    to: user.email,
    name: user.name,
    resetUrl: buildPasswordResetUrl(plainToken)
  });

  await createAuditTrailSafe({
    userId: auth.user.id,
    action: "USER_FORCE_RESET_SENT",
    entityType: "USER",
    entityId: user.id,
    method: request.method,
    pathname: new URL(request.url).pathname,
    statusCode: 200,
    summary: `Force reset password dikirim ke ${user.email}`
  });

  return NextResponse.json({
    message: "Email force reset password berhasil dikirim."
  });
}
