import { NextResponse } from "next/server";
import { issueEmailVerificationToken, sendEmailVerificationLink } from "@/lib/auth/verification";
import { prisma } from "@/lib/prisma";
import { buildAppUrl } from "@/lib/http/url";

function redirectTo(request: Request, path: string, params: Record<string, string>) {
  return NextResponse.redirect(buildAppUrl(request, path, params));
}

export async function POST(request: Request) {
  const formData = await request.formData();
  const email = typeof formData.get("email") === "string" ? formData.get("email")!.toString().trim().toLowerCase() : "";

  if (!email) {
    return redirectTo(request, "/verify", { error: "missing_email" });
  }

  try {
    const user = await prisma.user.findUnique({ where: { email } });

    if (user && !user.emailVerifiedAt) {
      const { token } = await issueEmailVerificationToken(user.id);
      const sendResult = await sendEmailVerificationLink(request, email, token);

      const verifyParams: Record<string, string> = {
        email,
        sent: sendResult.sent ? "1" : "0",
      };

      if (!sendResult.sent) {
        verifyParams.error = "email_delivery_failed";
      }

      return redirectTo(request, "/verify", verifyParams);
    }

    return redirectTo(request, "/verify", { email, sent: "1" });
  } catch {
    return redirectTo(request, "/verify", { email, error: "server_error" });
  }
}
