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.
 */
export async function resolveOrgId(headerValue: string | null): Promise<string | null> {
  const val = headerValue?.trim()
  if (!val) return null

  // 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 },
  })
  return byId?.id ?? null
}
