/**
 * syncTierToTenant — zync-subscription spec (Task 5).
 *
 * Propagates a tier change from the authoritative `zync_subscriptions.tier`
 * to the denormalised `tenants.tier` column read by every entitlement check.
 *
 * Must be called on every tier mutation:
 *  - Admin override (PATCH /api/admin/tenants/:slug/subscription)
 *  - Trial downgrade (cron/subscription-trial-check)
 *  - Webhook activation (subscription.updated / invoice.paid)
 *
 * Entitlement checks (requireTier, useTierGate, meetsMinimumTier) remain
 * unaware of zync_subscriptions — they read tenants.tier from the session.
 * This function is the bridge.
 */
import { sql } from 'drizzle-orm'
import type { TenantTier } from '@zync/types'
import type { Db } from '@zync/db/queries'

/**
 * Update `tenants.tier` for the given tenantId.
 * Uses a raw SQL execute to avoid a circular dependency on the shared schema
 * package; the tenants table is owned by foundation-auth-rbac and the Drizzle
 * object is not safe to import here without creating an import cycle.
 */
export async function syncTierToTenant(
  db: Db,
  tenantId: string,
  tier: TenantTier,
): Promise<void> {
  await db.execute(sql`UPDATE tenants SET tier = ${tier} WHERE id = ${tenantId}`)
}
