CREATE TABLE IF NOT EXISTS gateway.legacy_id_mappings (
    source_system varchar(64) NOT NULL,
    entity_type varchar(128) NOT NULL,
    legacy_id text NOT NULL,
    new_id uuid NOT NULL,
    metadata jsonb NOT NULL DEFAULT '{}'::jsonb,
    imported_at timestamptz NOT NULL DEFAULT clock_timestamp(),
    PRIMARY KEY (source_system, entity_type, legacy_id),
    UNIQUE (source_system, entity_type, new_id),
    CHECK (length(source_system) BETWEEN 1 AND 64),
    CHECK (length(entity_type) BETWEEN 1 AND 128),
    CHECK (length(legacy_id) BETWEEN 1 AND 256)
);

CREATE INDEX IF NOT EXISTS legacy_id_mappings_new_id_idx
    ON gateway.legacy_id_mappings (new_id);

COMMENT ON TABLE gateway.legacy_id_mappings IS
    'Idempotent compatibility map from legacy entity IDs to deterministic UUIDv5 IDs.';
