import prisma from "@/lib/prisma"

/**
 * Resolve organization ID from x-org-id header.
 * The header may contain a slug or a direct ID — we try slug first, then ID.
 * Falls back to first org if none specified (single-tenant mode).
 */
export async function resolveOrgId(headerValue: string | null): Promise<string | null> {
  if (!prisma) return null
  const val = headerValue?.trim()

  if (val && val !== "demo") {
    // Try by slug first (most common from frontend)
    const bySlug = await prisma.organization.findFirst({
      where: {
        OR: [
          { slug: val },
          { slug: { startsWith: val } },
        ],
      },
      select: { id: true },
    })
    if (bySlug) return bySlug.id

    // Try direct ID
    const byId = await prisma.organization.findUnique({
      where: { id: val },
      select: { id: true },
    })
    if (byId) return byId.id
  }

  // Single-tenant fallback: use first org
  const first = await prisma.organization.findFirst({
    select: { id: true },
    orderBy: { createdAt: "asc" },
  })
  return first?.id ?? null
}
