-- Migration 152: reconcile iace_projects with the current Go schema.
-- ==========================================================================
-- The iace tables were created ad-hoc (no CREATE migration) and drifted across
-- environments. The consolidation copied an OLDER iace_projects into the local
-- `compliance` schema: it carried legacy columns (intended_use,
-- limits_description, reasonably_foreseeable_misuse, completeness_pct,
-- can_export) and lacked the columns the current store layer reads/writes
-- (store_projects.go CreateProject/GetProject): customer_name, description,
-- narrative_text, ce_marking_target, completeness_score, risk_summary,
-- triggered_regulations, archived_at.
--
-- This migration brings the table to the code's expectation. Idempotent and
-- guarded so it is a no-op where the table already matches. Legacy columns are
-- only made nullable (not dropped) so any historical data survives while the
-- current INSERT (which omits them) no longer fails on NOT NULL.
-- ==========================================================================

ALTER TABLE iace_projects
    ADD COLUMN IF NOT EXISTS parent_project_id      uuid,
    ADD COLUMN IF NOT EXISTS customer_name          text,
    ADD COLUMN IF NOT EXISTS description            text,
    ADD COLUMN IF NOT EXISTS narrative_text         text,
    ADD COLUMN IF NOT EXISTS ce_marking_target      text,
    ADD COLUMN IF NOT EXISTS completeness_score     double precision,
    ADD COLUMN IF NOT EXISTS risk_summary           jsonb,
    ADD COLUMN IF NOT EXISTS triggered_regulations  jsonb,
    ADD COLUMN IF NOT EXISTS archived_at            timestamptz;

-- Relax legacy NOT NULL columns the current code never writes, so INSERTs that
-- omit them succeed. DROP NOT NULL is a no-op when already nullable; the guard
-- skips columns that do not exist in this schema variant.
DO $$
DECLARE
    col text;
BEGIN
    FOREACH col IN ARRAY ARRAY[
        'intended_use', 'limits_description', 'reasonably_foreseeable_misuse',
        'completeness_pct', 'can_export'
    ] LOOP
        IF EXISTS (
            SELECT 1 FROM information_schema.columns
            WHERE table_name = 'iace_projects' AND column_name = col
        ) THEN
            EXECUTE format('ALTER TABLE iace_projects ALTER COLUMN %I DROP NOT NULL', col);
        END IF;
    END LOOP;
END $$;
