import { integer, pgEnum, pgTable, primaryKey, text, timestamp, uuid } from 'drizzle-orm/pg-core'

/**
 * Two-party data release. Fixed by #14.
 *
 * One rule set, expressed once. `release_level` collapses the four inputs
 * #12 named — audience membership, stage, participation state, acknowledgement —
 * into a single enum. Every sensitive field belongs to a disclosure class.
 * The matrix says which class opens at which level, and RLS policies compare
 * the two. Nothing else encodes lifecycle.
 *
 * The functions live in migrations/custom because Drizzle cannot diff them.
 */

export const releaseLevel = pgEnum('release_level', [
  /** Not in the audience. Sees nothing at all. */
  'none',
  /** In the audience, pre-acknowledgement. Teaser only. */
  'invited',
  /** Acknowledgement passed. Full RFP body, exact quantities. */
  'acknowledged',
  /** Has submitted; the field is still sealed. */
  'submitted',
  /** Deadline passed — the whole field opened at once (#14 decision 2). */
  'open',
  'evaluating',
  'finalist',
  'awarded',
])

export const disclosureClass = pgEnum('disclosure_class', [
  'vendor_identity',
  'participation_signal',
  'scenario_quantity',
  'answer_text',
  'exception_text',
  'price_quote',
  'derived_cost',
  'vault_document',
  'own_scoring',
])

/**
 * VERSIONED. Without a version history a past release cannot be reconstructed
 * when an award is protested — the one thing the function form costs (#14).
 * Seeded by a custom migration; a rule change is a new version, never an update.
 */
export const releaseMatrix = pgTable('release_matrix', {
  version: integer('version').notNull(),
  class: disclosureClass('class').notNull(),
  level: releaseLevel('level').notNull(),
  released: text('released').notNull(),
  effectiveFrom: timestamp('effective_from', { withTimezone: true }).notNull().defaultNow(),
}, (t) => [primaryKey({ columns: [t.version, t.class, t.level] })])

/**
 * Export mirrors read exactly (#14 decision 5). The log is the accountability,
 * not the restriction — a retailer who bulk-extracts every losing price has
 * done so on the record.
 */
export const exportEvent = pgTable('export_event', {
  id: uuid('id').primaryKey().defaultRandom(),
  actorId: uuid('actor_id').notNull(),
  orgId: uuid('org_id').notNull(),
  capability: text('capability').notNull(),
  solicitationId: uuid('solicitation_id').notNull(),
  classes: text('classes').array().notNull(),
  rowCount: integer('row_count').notNull(),
  at: timestamp('at', { withTimezone: true }).notNull().defaultNow(),
})
