-- V78: person_relationships.from_year/to_year (integer) → from_date/to_date (date)
-- plus NOT NULL precision columns, mirroring persons.{birth,death}_date (V76 / ADR-039).
-- Existing years are backfilled as YYYY-01-01 at YEAR precision (ADR-044).
-- One-way migration: rollback is a targeted pg_restore -t person_relationships from
-- the pre-deploy backup (see docs/DEPLOYMENT.md). The column drop is NOT
-- rolling-deploy-safe — stop the old JAR before running this migration.

-- Pre-check (data quality gate — not a race guard): abort on corrupt year data
-- before any DDL runs. Single-writer family archive, so no race window matters.
DO $$ BEGIN
  IF EXISTS (SELECT 1 FROM person_relationships WHERE from_year IS NOT NULL AND to_year IS NOT NULL AND from_year > to_year)
    THEN RAISE EXCEPTION 'V78 aborted: % relationships have from_year > to_year — fix data before migrating',
      (SELECT COUNT(*) FROM person_relationships WHERE from_year IS NOT NULL AND to_year IS NOT NULL AND from_year > to_year);
  END IF;
  IF EXISTS (SELECT 1 FROM person_relationships WHERE from_year = 0 OR to_year = 0)
    THEN RAISE EXCEPTION 'V78 aborted: person_relationships table contains from_year=0 or to_year=0 rows — clean data before migrating';
  END IF;
END $$;

ALTER TABLE person_relationships ADD COLUMN from_date date;
ALTER TABLE person_relationships ADD COLUMN from_date_precision varchar(16) NOT NULL DEFAULT 'UNKNOWN';
ALTER TABLE person_relationships ADD COLUMN to_date date;
ALTER TABLE person_relationships ADD COLUMN to_date_precision varchar(16) NOT NULL DEFAULT 'UNKNOWN';

UPDATE person_relationships SET from_date = make_date(from_year, 1, 1), from_date_precision = 'YEAR'
    WHERE from_year IS NOT NULL;
UPDATE person_relationships SET to_date = make_date(to_year, 1, 1), to_date_precision = 'YEAR'
    WHERE to_year IS NOT NULL;

-- Named constraints: readable Postgres error messages when violated.
ALTER TABLE person_relationships ADD CONSTRAINT chk_relationship_from_coherence
    CHECK ((from_date IS NULL) = (from_date_precision = 'UNKNOWN'));
ALTER TABLE person_relationships ADD CONSTRAINT chk_relationship_to_coherence
    CHECK ((to_date IS NULL) = (to_date_precision = 'UNKNOWN'));
ALTER TABLE person_relationships ADD CONSTRAINT chk_relationship_date_order
    CHECK (from_date IS NULL OR to_date IS NULL OR from_date <= to_date);
ALTER TABLE person_relationships ADD CONSTRAINT chk_relationship_from_precision_values
    CHECK (from_date_precision IN ('DAY', 'MONTH', 'SEASON', 'YEAR', 'RANGE', 'APPROX', 'UNKNOWN'));
ALTER TABLE person_relationships ADD CONSTRAINT chk_relationship_to_precision_values
    CHECK (to_date_precision IN ('DAY', 'MONTH', 'SEASON', 'YEAR', 'RANGE', 'APPROX', 'UNKNOWN'));

ALTER TABLE person_relationships DROP COLUMN from_year;
ALTER TABLE person_relationships DROP COLUMN to_year;
