import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";

type VerifyFailure = {
  valid: false;
  reason: "not_found" | "expired" | "accepted";
  orgName?: string;
  inviterName?: string;
};

type VerifySuccess = {
  valid: true;
  email: string;
  role: string;
  orgName: string;
  inviterName: string | null;
  hasExistingAccount: boolean;
};

async function resolveInviterName(invitedById: string): Promise<string | null> {
  const inviter = await prisma.user.findUnique({
    where: { id: invitedById },
    select: { displayName: true, username: true, email: true },
  });
  if (!inviter) return null;
  return inviter.displayName || inviter.username || inviter.email || null;
}

export async function GET(req: NextRequest) {
  const token = req.nextUrl.searchParams.get("token");
  if (!token) {
    const body: VerifyFailure = { valid: false, reason: "not_found" };
    return NextResponse.json(body);
  }

  const invitation = await prisma.invitation.findUnique({
    where: { token },
    include: { organization: { select: { name: true } } },
  });

  if (!invitation) {
    const body: VerifyFailure = { valid: false, reason: "not_found" };
    return NextResponse.json(body);
  }

  const inviterName = await resolveInviterName(invitation.invitedById);

  if (invitation.acceptedAt) {
    const body: VerifyFailure = {
      valid: false,
      reason: "accepted",
      orgName: invitation.organization.name,
      inviterName: inviterName ?? undefined,
    };
    return NextResponse.json(body);
  }

  if (invitation.expiresAt < new Date()) {
    const body: VerifyFailure = {
      valid: false,
      reason: "expired",
      orgName: invitation.organization.name,
      inviterName: inviterName ?? undefined,
    };
    return NextResponse.json(body);
  }

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

  const body: VerifySuccess = {
    valid: true,
    email: invitation.email,
    role: invitation.role,
    orgName: invitation.organization.name,
    inviterName,
    hasExistingAccount: !!existingUser,
  };
  return NextResponse.json(body);
}
