import { pgEnum, pgTable, text, timestamp, uuid, integer } from 'drizzle-orm/pg-core'
import { organization } from './org.js'

/**
 * Entitlement. Fixed by #20, reversed in part by #34.
 *
 * There is no free vendor tier. A $100/mo floor gates participation entirely.
 * Tiers scale on seats and AI capability — never on volume, never per-retailer.
 *
 * Entitlement is NEVER expressed as row visibility. RLS answers "whose row is
 * this"; a lapsed vendor still owns every row they owned yesterday. Policies
 * must not reference entitlement at all (#20 decision 3).
 */

export const tier = pgEnum('tier', ['base', 'pro', 'enterprise'])

export const SEATS: Record<'base' | 'pro' | 'enterprise', number | null> = {
  base: 2,
  pro: 10,
  enterprise: null,
}

export const entitlement = pgTable('entitlement', {
  id: uuid('id').primaryKey().defaultRandom(),
  beneficiaryOrgId: uuid('beneficiary_org_id').notNull().references(() => organization.id),
  /**
   * In v1 always equals the beneficiary. One column now so retailer sponsorship
   * can return without a migration (#20 decision 4, deferred rather than declined).
   */
  payerOrgId: uuid('payer_org_id').notNull().references(() => organization.id),
  tier: tier('tier').notNull(),
  seats: integer('seats'),
  startedAt: timestamp('started_at', { withTimezone: true }).notNull().defaultNow(),
  /** On lapse, live participations run to completion (#34 decision 4). */
  lapsedAt: timestamp('lapsed_at', { withTimezone: true }),
})
