create table if not exists eventhub.source_master_entity (
    id uuid primary key,
    tenant_key text not null,
    event_source_id integer not null references eventhub.event_source(id),
    entity_type text not null,
    source_entity_id text not null,
    source_external_key text,
    display_name text,
    active boolean,
    valid_from timestamptz,
    valid_to timestamptz,
    source_updated_at timestamptz,
    payload jsonb not null default '{}'::jsonb,
    created_at timestamptz not null default now(),
    updated_at timestamptz not null default now(),
    constraint ux_source_master_entity unique (tenant_key, event_source_id, entity_type, source_entity_id),
    constraint chk_source_master_entity_valid_time_order check (valid_from is null or valid_to is null or valid_from < valid_to)
);

create table if not exists eventhub.source_master_relation (
    id uuid primary key,
    tenant_key text not null,
    event_source_id integer not null references eventhub.event_source(id),
    relation_key text not null,
    relation_type text not null,
    from_entity_type text not null,
    from_source_entity_id text not null,
    to_entity_type text not null,
    to_source_entity_id text not null,
    valid_from timestamptz,
    valid_to timestamptz,
    source_updated_at timestamptz,
    payload jsonb not null default '{}'::jsonb,
    created_at timestamptz not null default now(),
    updated_at timestamptz not null default now(),
    constraint ux_source_master_relation unique (tenant_key, event_source_id, relation_key),
    constraint chk_source_master_relation_valid_time_order check (valid_from is null or valid_to is null or valid_from < valid_to)
);

create index if not exists idx_source_master_entity_type_key
    on eventhub.source_master_entity(tenant_key, event_source_id, entity_type, source_external_key)
    where source_external_key is not null;

create index if not exists idx_source_master_entity_payload_gin
    on eventhub.source_master_entity using gin(payload);

create index if not exists idx_source_master_relation_from
    on eventhub.source_master_relation(tenant_key, event_source_id, from_entity_type, from_source_entity_id, relation_type);

create index if not exists idx_source_master_relation_to
    on eventhub.source_master_relation(tenant_key, event_source_id, to_entity_type, to_source_entity_id, relation_type);

create index if not exists idx_source_master_relation_payload_gin
    on eventhub.source_master_relation using gin(payload);
