/**
 * GET /api/auth/check-access — Beta access gate.
 *
 * Three-tier check:
 * 1. Is email in ALLOWED_EMAILS env var? → allowed
 * 2. Does the user belong to any organization in the database? → allowed
 *    (they were invited by someone with access)
 * 3. Neither? → blocked
 */

import { NextResponse } from "next/server";
import { currentUser } from "@clerk/nextjs/server";
import { prisma } from "@/lib/prisma";
import { getCurrentUser } from "@/lib/auth";

export const dynamic = "force-dynamic";

export async function GET() {
  const clerkUser = await currentUser();
  if (!clerkUser) {
    return NextResponse.json({ allowed: false });
  }

  const envVal = process.env.ALLOWED_EMAILS;

  // If no ALLOWED_EMAILS set, allow everyone (fail open)
  if (!envVal || envVal.trim() === "") {
    return NextResponse.json({ allowed: true });
  }

  // Gather ALL emails from Clerk
  const primaryEmail = clerkUser.primaryEmailAddress?.emailAddress?.toLowerCase()?.trim() || "";
  const allEmails = (clerkUser.emailAddresses || []).map((ea) => ea.emailAddress?.toLowerCase()?.trim() || "").filter(Boolean);
  if (primaryEmail && !allEmails.includes(primaryEmail)) allEmails.push(primaryEmail);

  // Check 1: Is email in ALLOWED_EMAILS?
  const allowedList = envVal.split(",").map((e) => e.toLowerCase().trim()).filter(Boolean);
  const emailAllowed = allEmails.some((email) => allowedList.includes(email));

  if (emailAllowed) {
    return NextResponse.json({ allowed: true });
  }

  // Check 2: Does the user belong to any organization in the database?
  try {
    const dbUser = await getCurrentUser();
    if (dbUser) {
      const membershipCount = await prisma.orgMembership.count({
        where: { userId: dbUser.id },
      });
      if (membershipCount > 0) {
        return NextResponse.json({ allowed: true });
      }
    }
  } catch {
    // DB check failed — don't block, fall through to denied
  }

  // Check 3: Neither — blocked
  console.warn("[check-access] denied — no email match and no org membership");

  return NextResponse.json({ allowed: false });
}
