import { eq } from "drizzle-orm";

import { db } from "@/lib/db";
import { orgSubscription } from "@/lib/db/schema";

/**
 * Returns the orgSubscription row for the given org. If missing, lazily
 * inserts a free-plan stub and returns the inserted row. Idempotent: safe
 * to call from any read path (dashboard layout, settings/billing, pricing).
 *
 * Why: databaseHooks.user.create.after seeds the stub for new signups, but
 * orgs created before that hook (legacy admin orgs) lack the row and
 * crash any consumer that asserts its existence.
 */
export async function ensureOrgSubscription(orgId: string) {
  const [existing] = await db
    .select()
    .from(orgSubscription)
    .where(eq(orgSubscription.organizationId, orgId))
    .limit(1);
  if (existing) return existing;

  const [inserted] = await db
    .insert(orgSubscription)
    .values({
      id: `sub_${orgId}`,
      organizationId: orgId,
      plan: "free",
      status: "active",
      // Stripe fields stay null until first checkout.
    })
    .onConflictDoNothing({ target: orgSubscription.organizationId })
    .returning();

  if (inserted) return inserted;

  // Race condition: another request inserted between our select and insert.
  // Re-fetch and return.
  const [racedRow] = await db
    .select()
    .from(orgSubscription)
    .where(eq(orgSubscription.organizationId, orgId))
    .limit(1);
  if (!racedRow) throw new Error(`Failed to ensure orgSubscription for ${orgId}`);
  return racedRow;
}
