import { eq } from "drizzle-orm";

import { getStripe } from "@/lib/billing/stripe";
import { db } from "@/lib/db";
import { member, organization, orgSubscription, user } from "@/lib/db/schema";

/* Resolves the org's stripeCustomerId. If absent, creates a Stripe Customer
   with metadata.orgId for later identification in webhooks, then persists
   the id in es_org_subscription. Idempotent: re-runs return the cached id. */
export async function ensureStripeCustomer(organizationId: string): Promise<string> {
  const subs = await db
    .select({
      stripeCustomerId: orgSubscription.stripeCustomerId,
      orgName: organization.name,
    })
    .from(orgSubscription)
    .innerJoin(organization, eq(organization.id, orgSubscription.organizationId))
    .where(eq(orgSubscription.organizationId, organizationId))
    .limit(1);

  if (subs.length === 0) {
    throw new Error(`No subscription row for org ${organizationId}`);
  }
  if (subs[0]!.stripeCustomerId) return subs[0]!.stripeCustomerId;

  // First member of the org as the Customer email/name.
  const owners = await db
    .select({ email: user.email, name: user.name })
    .from(member)
    .innerJoin(user, eq(user.id, member.userId))
    .where(eq(member.organizationId, organizationId))
    .limit(5);
  const ownerRow = owners[0];

  const customer = await getStripe().customers.create({
    email: ownerRow?.email,
    name: subs[0]!.orgName,
    metadata: { orgId: organizationId },
  });

  await db
    .update(orgSubscription)
    .set({ stripeCustomerId: customer.id, updatedAt: new Date() })
    .where(eq(orgSubscription.organizationId, organizationId));

  return customer.id;
}
