CREATE TABLE IF NOT EXISTS gateway.legacy_import_batches (
    id uuid PRIMARY KEY,
    source_system text NOT NULL CHECK (length(source_system) BETWEEN 1 AND 64),
    source_checksum char(64) NOT NULL,
    status text NOT NULL CHECK (status IN ('staged','validated','applied','failed')),
    record_count integer NOT NULL CHECK (record_count >= 0),
    entity_counts jsonb NOT NULL DEFAULT '{}'::jsonb,
    error text NOT NULL DEFAULT '',
    created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
    completed_at timestamptz,
    UNIQUE (source_system, source_checksum)
);

CREATE TABLE IF NOT EXISTS gateway.legacy_import_records (
    first_seen_batch_id uuid NOT NULL REFERENCES gateway.legacy_import_batches(id),
    source_system text NOT NULL,
    entity_type text NOT NULL,
    legacy_id text NOT NULL,
    new_id uuid NOT NULL,
    payload jsonb NOT NULL,
    payload_checksum char(64) NOT NULL,
    target_table text NOT NULL DEFAULT '',
    applied_at timestamptz,
    error text NOT NULL DEFAULT '',
    PRIMARY KEY (source_system, entity_type, legacy_id),
    UNIQUE (source_system, entity_type, new_id)
);

CREATE TABLE IF NOT EXISTS gateway.legacy_import_batch_records (
    batch_id uuid NOT NULL REFERENCES gateway.legacy_import_batches(id) ON DELETE CASCADE,
    source_system text NOT NULL,
    entity_type text NOT NULL,
    legacy_id text NOT NULL,
    payload_checksum char(64) NOT NULL,
    PRIMARY KEY (batch_id, entity_type, legacy_id),
    FOREIGN KEY (source_system, entity_type, legacy_id)
        REFERENCES gateway.legacy_import_records(source_system, entity_type, legacy_id)
);

CREATE INDEX IF NOT EXISTS legacy_import_records_pending_idx
    ON gateway.legacy_import_records (entity_type, legacy_id)
    WHERE applied_at IS NULL AND error = '';

COMMENT ON TABLE gateway.legacy_import_records IS
    'Validated immutable staging records. Sensitive legacy ciphertext is never treated as a usable new credential; domain transforms must decrypt and re-encrypt with the new purpose label.';
