-- Phase 4.1 — ticket-first IT Glue audit + Configuration support + cross-reference index.
--
-- Three things:
--   1. Add ticket linkage to existing audit + write tables (denormalized for
--      direct queries; the audit row is the source of truth).
--   2. Extend asset_type CHECK constraints to include 'configuration'.
--   3. New itglue_ticket_xrefs table — ticket↔asset linkage with relationship
--      type. Powers "tickets that touched this asset" + "docs this ticket
--      touched" views, and is the lookup index for the future RAG automation.

-- 1. Ticket linkage on audits + writes
ALTER TABLE itglue_asset_audits
  ADD COLUMN IF NOT EXISTS triggered_by_ticket_number TEXT,
  ADD COLUMN IF NOT EXISTS triggered_by_analysis_id UUID
    REFERENCES analyzer_analyses(id) ON DELETE SET NULL;

CREATE INDEX IF NOT EXISTS ix_itglue_asset_audits_ticket
  ON itglue_asset_audits (triggered_by_ticket_number)
  WHERE triggered_by_ticket_number IS NOT NULL;

ALTER TABLE itglue_writes
  ADD COLUMN IF NOT EXISTS triggered_by_ticket_number TEXT;

CREATE INDEX IF NOT EXISTS ix_itglue_writes_ticket
  ON itglue_writes (triggered_by_ticket_number)
  WHERE triggered_by_ticket_number IS NOT NULL;

-- 2. Extend asset_type to include 'configuration'
ALTER TABLE itglue_asset_audits
  DROP CONSTRAINT IF EXISTS itglue_asset_audits_asset_type_check;
ALTER TABLE itglue_asset_audits
  ADD CONSTRAINT itglue_asset_audits_asset_type_check
  CHECK (asset_type IN ('flexible_asset', 'configuration'));

ALTER TABLE itglue_writes
  DROP CONSTRAINT IF EXISTS itglue_writes_asset_type_check;
ALTER TABLE itglue_writes
  ADD CONSTRAINT itglue_writes_asset_type_check
  CHECK (asset_type IN ('flexible_asset', 'configuration'));

-- 3. Cross-reference table
CREATE TABLE IF NOT EXISTS itglue_ticket_xrefs (
  id              UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  ticket_number   TEXT NOT NULL,
  analysis_id     UUID REFERENCES analyzer_analyses(id) ON DELETE CASCADE,
  asset_type      TEXT NOT NULL
                    CHECK (asset_type IN ('flexible_asset','configuration','document')),
  asset_id        BIGINT NOT NULL,
  relationship    TEXT NOT NULL
                    CHECK (relationship IN ('referenced','updated','should_have_referenced')),
  source          TEXT NOT NULL
                    CHECK (source IN ('analyzer_referenced','audit_write','manual')),
  confidence      TEXT
                    CHECK (confidence IS NULL OR confidence IN ('high','medium','low')),
  details         JSONB,
  created_at      TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS ix_xrefs_ticket
  ON itglue_ticket_xrefs (ticket_number, created_at DESC);
CREATE INDEX IF NOT EXISTS ix_xrefs_asset
  ON itglue_ticket_xrefs (asset_type, asset_id, created_at DESC);
CREATE INDEX IF NOT EXISTS ix_xrefs_rel
  ON itglue_ticket_xrefs (relationship);

-- Dedup: same logical xref (ticket, analysis, asset, relationship, source)
-- inserted once. analysis_id is nullable, so coalesce to a sentinel UUID for
-- the unique-index purposes.
CREATE UNIQUE INDEX IF NOT EXISTS ux_xrefs_unique
  ON itglue_ticket_xrefs (
    ticket_number,
    COALESCE(analysis_id, '00000000-0000-0000-0000-000000000000'::uuid),
    asset_type,
    asset_id,
    relationship,
    source
  );

COMMENT ON TABLE itglue_ticket_xrefs IS
  'Ticket↔IT-Glue-asset linkage. relationship=referenced (analyzer cited the doc), '
  'updated (a ticket-driven audit produced a write), should_have_referenced '
  '(gap text indicates the asset should exist or be tagged). Powers asset-side '
  '"tickets that touched me" and ticket-side "docs this ticket touched" views.';
