import { integer, jsonb, pgEnum, pgTable, text, timestamp, uuid } from 'drizzle-orm/pg-core'
import { requirement, solicitation, solicitationDocument } from './solicitation.js'

/**
 * Extraction confirmation and the completeness sweep. Fixed by #16.
 *
 * The ledger is ordered by extraction uncertainty rather than document order,
 * so the least reliable items get the freshest attention. Rubber-stamping is
 * not preventable, only attributable — hence a confirmer per requirement.
 */

export const confirmationEvent = pgTable('confirmation_event', {
  id: uuid('id').primaryKey().defaultRandom(),
  requirementId: uuid('requirement_id').notNull().references(() => requirement.id),
  confirmedBy: uuid('confirmed_by').notNull(),
  corrected: text('corrected'),
  at: timestamp('at', { withTimezone: true }).notNull().defaultNow(),
})

export const sweepFindingKind = pgEnum('sweep_finding_kind', [
  /** Second pass asserts an obligation that no requirement covers. BLOCKS issue. */
  'asserted_obligation',
  /** Uncovered span with no obligation asserted. Reported, never gating. */
  'uncovered_span',
])

export const sweepFinding = pgTable('sweep_finding', {
  id: uuid('id').primaryKey().defaultRandom(),
  solicitationId: uuid('solicitation_id').notNull().references(() => solicitation.id),
  documentId: uuid('document_id').notNull().references(() => solicitationDocument.id),
  kind: sweepFindingKind('kind').notNull(),
  page: integer('page').notNull(),
  span: jsonb('span').$type<{ start: number; end: number }>().notNull(),
  quotedText: text('quoted_text').notNull(),
  /** Resolved by adding a requirement, or by a named human call of "not an obligation". */
  resolvedByRequirementId: uuid('resolved_by_requirement_id').references(() => requirement.id),
  dismissedBy: uuid('dismissed_by'),
  dismissedAt: timestamp('dismissed_at', { withTimezone: true }),
})

/**
 * The free but biased secondary detector (#33). Vendors report omissions that
 * help them and stay quiet on ones that hurt them. Recording it is the point:
 * a vendor who flagged an omission and was ignored is a witness at protest.
 */
export const vendorOmissionReport = pgTable('vendor_omission_report', {
  id: uuid('id').primaryKey().defaultRandom(),
  solicitationId: uuid('solicitation_id').notNull().references(() => solicitation.id),
  vendorOrgId: uuid('vendor_org_id').notNull(),
  body: text('body').notNull(),
  reportedAt: timestamp('reported_at', { withTimezone: true }).notNull().defaultNow(),
  actedOnAt: timestamp('acted_on_at', { withTimezone: true }),
  actedOnBy: uuid('acted_on_by'),
})
