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

/**
 * The cross-retailer document vault. Fixed by #13.
 *
 * Through-line: we establish facts, retailers make judgements. The vendor
 * attests, we validate only machine-checkable structure, and verification is
 * a graph of retailer acceptances rather than a platform assertion.
 */

/** We curate a small typed catalogue. Contents are #27. */
export const documentType = pgTable('document_type', {
  id: text('id').primaryKey(),
  label: text('label').notNull(),
  /** Each type carries a validator and an expiry rule — that is why it is typed. */
  expiryRule: text('expiry_rule'),
})

export const expiryState = pgEnum('expiry_state', ['current', 'expiring_soon', 'expired'])

export const vaultDocument = pgTable('vault_document', {
  id: uuid('id').primaryKey().defaultRandom(),
  vendorOrgId: uuid('vendor_org_id').notNull().references(() => organization.id),
  typeId: text('type_id').notNull().references(() => documentType.id),
  blobRef: text('blob_ref').notNull(),
  sha256: text('sha256').notNull(),
  expiresAt: timestamp('expires_at', { withTimezone: true }),
  /**
   * Derived, recomputed on a clock rather than only on write — the reason the
   * layout needs a scheduler at all (#13 decision 4). Never entitlement-gated:
   * entitlement gates vendor convenience, never retailer-facing correctness.
   */
  expiryState: expiryState('expiry_state').notNull().default('current'),
  expiryComputedAt: timestamp('expiry_computed_at', { withTimezone: true }),
}).enableRLS()

/**
 * Acceptances accumulate into the reuse benefit. Cross-retailer signals are
 * anonymous by default: a retailer sees an unattributed count, never which.
 *
 * Reading these rows across retailers is a PRIVILEGED PATH — see
 * src/db/privileged.ts. The k-floor lives there, not in application code.
 */
export const retailerAcceptance = pgTable('retailer_acceptance', {
  documentId: uuid('document_id').notNull().references(() => vaultDocument.id),
  retailerOrgId: uuid('retailer_org_id').notNull().references(() => organization.id),
  acceptedAt: timestamp('accepted_at', { withTimezone: true }).notNull().defaultNow(),
  /** Disclosure is the vendor's asset to trade — opt-in, per document per retailer. */
  vendorDisclosedName: text('vendor_disclosed_name'),
}, (t) => [primaryKey({ columns: [t.documentId, t.retailerOrgId] })]).enableRLS()
