import { createDb, eq, organizations } from '@bmm/db';
import type { Plan } from '@bmm/llm';

const db = createDb();

/** Look up an org's current plan. Defaults to 'hobby' if the org row is gone
 *  for any reason — fail-closed to the least expensive tier. */
export async function getOrgPlan(orgId: string): Promise<Plan> {
  const [row] = await db
    .select({ plan: organizations.plan })
    .from(organizations)
    .where(eq(organizations.id, orgId))
    .limit(1);
  return (row?.plan ?? 'hobby') as Plan;
}

export interface OrgBilling {
  plan: Plan;
  suspended: boolean;
  suspendedReason: string | null;
}

/** Like getOrgPlan but also reports suspension state. Use in routes that
 *  should refuse new work when a subscription is past-due / unpaid. */
export async function getOrgBilling(orgId: string): Promise<OrgBilling> {
  const [row] = await db
    .select({
      plan: organizations.plan,
      suspended: organizations.suspended,
      suspendedReason: organizations.suspendedReason,
    })
    .from(organizations)
    .where(eq(organizations.id, orgId))
    .limit(1);
  return {
    plan: (row?.plan ?? 'hobby') as Plan,
    suspended: row?.suspended ?? false,
    suspendedReason: row?.suspendedReason ?? null,
  };
}

/** Max MCP servers per org by plan. Enforced at POST /v1/servers. */
export const SERVER_LIMITS: Record<Plan, number> = {
  hobby: 1,
  pro: 5,
  team: 25,
  enterprise: Number.MAX_SAFE_INTEGER,
};
