import { NextResponse } from "next/server";

import { sendEmailVerificationEmail } from "@/features/auth/lib/auth-emails";
import {
  buildEmailVerificationUrl,
  issueEmailVerificationToken
} from "@/features/auth/lib/email-verification";
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 });
  }

  if (user.emailVerifiedAt) {
    return NextResponse.json({ message: "Email user sudah diverifikasi." });
  }

  const { plainToken } = await issueEmailVerificationToken(user.id);
  await sendEmailVerificationEmail({
    to: user.email,
    name: user.name,
    verifyUrl: buildEmailVerificationUrl(plainToken)
  });

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

  return NextResponse.json({
    message: "Email verifikasi berhasil dikirim."
  });
}
