-- 070_rmd_audit_results.sql
-- Cache table for RMD filing deficiency audit results.
-- Populated by scripts/workers/fcc_rmd_auditor.py.

BEGIN;

CREATE TABLE IF NOT EXISTS fcc_rmd_audit_results (
    id                  SERIAL PRIMARY KEY,
    fcc_rmd_id          INTEGER,  -- soft FK to fcc_rmd(id) if table exists
    rmd_number          TEXT NOT NULL,
    frn                 TEXT,
    business_name       TEXT,
    -- Structured data findings
    structured_checks   JSONB NOT NULL DEFAULT '[]',
    structured_score    INTEGER NOT NULL DEFAULT 0,
    -- PDF analysis findings (null until PDF analyzed)
    pdf_checks          JSONB,
    pdf_score           INTEGER,
    pdf_downloaded      BOOLEAN NOT NULL DEFAULT FALSE,
    pdf_text_length     INTEGER,
    -- Overall
    total_deficiencies  INTEGER NOT NULL DEFAULT 0,
    severity            TEXT CHECK (severity IN ('critical', 'major', 'minor', 'clean')),
    -- Timestamps
    audited_at          TIMESTAMPTZ NOT NULL DEFAULT now(),
    pdf_audited_at      TIMESTAMPTZ,
    updated_at          TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE UNIQUE INDEX IF NOT EXISTS idx_rmd_audit_rmd_number ON fcc_rmd_audit_results(rmd_number);
CREATE INDEX IF NOT EXISTS idx_rmd_audit_frn ON fcc_rmd_audit_results(frn);
CREATE INDEX IF NOT EXISTS idx_rmd_audit_severity ON fcc_rmd_audit_results(severity) WHERE severity != 'clean';

COMMIT;
