import { NextResponse } from "next/server";
import { z } from "zod";

import { sendEmailVerificationEmail } from "@/features/auth/lib/auth-emails";
import {
  buildEmailVerificationUrl,
  issueEmailVerificationToken
} from "@/features/auth/lib/email-verification";
import { createAuditTrailSafe } from "@/lib/audit-trail";
import { prisma } from "@/lib/prisma";

const resendVerificationSchema = z.object({
  email: z.string().trim().email("Email tidak valid")
});

export async function POST(request: Request) {
  try {
    const parsed = resendVerificationSchema.safeParse(await request.json());
    if (!parsed.success) {
      return NextResponse.json(
        {
          message: "Validasi gagal",
          errors: parsed.error.flatten().fieldErrors
        },
        { status: 422 }
      );
    }

    const email = parsed.data.email.toLowerCase();
    const user = await prisma.user.findFirst({
      where: {
        email,
        status: "ACTIVE",
        emailVerifiedAt: null
      }
    });

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

      await createAuditTrailSafe({
        userId: user.id,
        action: "EMAIL_VERIFICATION_RESENT",
        entityType: "AUTH",
        entityId: user.id,
        method: request.method,
        pathname: new URL(request.url).pathname,
        statusCode: 200,
        summary: "Kirim ulang email verifikasi"
      });
    }

    return NextResponse.json({
      message: "Jika email membutuhkan verifikasi, link verifikasi sudah dikirim."
    });
  } catch (error) {
    return NextResponse.json(
      {
        message: error instanceof Error ? error.message : "Gagal mengirim email verifikasi"
      },
      { status: 500 }
    );
  }
}
