// P5 Item 2 — XAI court-defensibility: decision_scoring_outputs table.
//
// D-4 architect PASS (2026-06-07) — six decisions locked:
//   Q1: new table (Option 1B — dedicated table)
//   Q2: schema + UNIQUE(tenant_id, decision_id) + check constraints
//   Q3: standard RLS table #70
//   Q4: ENCRYPTION REQUIRED — reasoning_text + factors_json encrypted via
//       pii-encryption.ts (treatment i, tenant-scoped key) before any prod write.
//       The columns below store ciphertext only — never raw values.
//   Q5: W-A synchronous inline (compute → persist → return, atomic)
//   Q6: KYT-path only (scoreThreat() call site in routes.ts)
//
// Encrypt-before-write discipline: see server/lib/persist-threat-decision.ts.
// RLS discipline: see server/lib/rls-init.ts TENANT_TABLES entry.
// Conformance coverage: see server/lib/schema-conformance.ts PII_COLUMNS entries.

import {
  pgTable,
  serial,
  text,
  integer,
  real,
  timestamp,
  uniqueIndex,
  check,
} from "drizzle-orm/pg-core";
import { sql } from "drizzle-orm";
import { createInsertSchema } from "drizzle-zod";
import { z } from "zod";

export const decisionScoringOutputs = pgTable(
  "decision_scoring_outputs",
  {
    id:                 serial("id").primaryKey(),
    tenantId:           text("tenant_id").notNull(),
    decisionId:         text("decision_id").notNull(),
    scoringPath:        text("scoring_path").notNull(),
    modelIdentifier:    text("model_identifier").notNull(),
    riskScore:          integer("risk_score").notNull(),
    confidence:         real("confidence"),
    reasoningText:      text("reasoning_text").notNull(),
    factorsJson:        text("factors_json").notNull(),
    auditChainEntryId:  integer("audit_chain_entry_id"),
    createdAt:          timestamp("created_at").notNull().defaultNow(),
  },
  (t) => [
    uniqueIndex("dso_tenant_decision_unique").on(t.tenantId, t.decisionId),
    check("dso_risk_score_range",   sql`${t.riskScore} BETWEEN 0 AND 100`),
    check("dso_confidence_range",   sql`${t.confidence} IS NULL OR (${t.confidence} >= 0 AND ${t.confidence} <= 1)`),
  ],
);

export const insertDecisionScoringOutputSchema = createInsertSchema(
  decisionScoringOutputs,
).omit({ id: true, createdAt: true });

export type DecisionScoringOutput       = typeof decisionScoringOutputs.$inferSelect;
export type InsertDecisionScoringOutput = z.infer<typeof insertDecisionScoringOutputSchema>;
