import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/auth";
import { sendVerificationEmail } from "@/lib/email-sender";
import { prisma } from "@/lib/db";

export async function POST(req: NextRequest) {
  try {
    const session = await auth();
    if (!session?.user?.id) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const user = await prisma.user.findUnique({
      where: { id: session.user.id },
      select: { email: true, emailVerified: true },
    });

    if (!user) {
      return NextResponse.json({ error: "User not found" }, { status: 404 });
    }

    if (user.emailVerified) {
      return NextResponse.json({ error: "Email already verified" }, { status: 400 });
    }

    const baseUrl = new URL(req.url).origin;
    await sendVerificationEmail(user.email, baseUrl);

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error("[verify-email/send] Error:", error);
    return NextResponse.json(
      { error: "Failed to send verification email" },
      { status: 500 }
    );
  }
}
