-- AEG-X-009 / ADR-DATA-001: make dataset freeze explicit and append-only.
-- This migration does not create or seed a dataset. It only hardens the existing
-- evaluation.dataset_manifest boundary.

alter table evaluation.dataset_manifest
    drop constraint if exists dataset_manifest_status_check;

alter table evaluation.dataset_manifest
    add constraint dataset_manifest_status_check
    check (status in ('PROPOSED', 'APPROVED', 'FROZEN', 'QUARANTINED', 'RETIRED'));

alter table evaluation.dataset_manifest
    drop constraint if exists dataset_manifest_frozen_approval_check;

alter table evaluation.dataset_manifest
    add constraint dataset_manifest_frozen_approval_check
    check (
        status <> 'FROZEN'
        or (approved_by is not null and approved_at is not null and frozen_at is not null)
    );

create or replace function evaluation.reject_dataset_manifest_mutation()
returns trigger as $$
begin
    raise exception 'evaluation.dataset_manifest is append-only; create a correction record';
end;
$$ language plpgsql;

drop trigger if exists dataset_manifest_no_update on evaluation.dataset_manifest;
create trigger dataset_manifest_no_update
before update or delete on evaluation.dataset_manifest
for each row execute function evaluation.reject_dataset_manifest_mutation();
