create table eventhub.vehicle (
    id uuid primary key,
    tenant_key text not null,
    event_source_id integer not null references eventhub.event_source(id),
    created_at timestamptz not null default now(),
    updated_at timestamptz not null default now()
);

create table eventhub.vehicle_identifier (
    id uuid primary key,
    vehicle_id uuid not null references eventhub.vehicle(id) on delete cascade,
    tenant_key text not null,
    event_source_id integer not null references eventhub.event_source(id),
    identifier_type text not null,
    nation text,
    identifier_value 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 chk_vehicle_identifier_valid_time_order
        check (valid_from is null or valid_to is null or valid_from <= valid_to),
    constraint chk_vehicle_identifier_nation_for_vrn
        check (
            identifier_type <> 'VRN'
            or nation is not null
        )
);

create index idx_vehicle_lookup_ctx
    on eventhub.vehicle(tenant_key, event_source_id, updated_at desc);

create index idx_vehicle_identifier_lookup
    on eventhub.vehicle_identifier(
        tenant_key, event_source_id, identifier_type, nation, identifier_value, valid_from desc
    );

create unique index ux_vehicle_identifier_exact
    on eventhub.vehicle_identifier(
        vehicle_id,
        identifier_type,
        coalesce(nation, ''),
        identifier_value,
        coalesce(valid_from, '-infinity'::timestamptz),
        coalesce(valid_to, 'infinity'::timestamptz)
    );

alter table eventhub.event
    rename column vehicle_entity_id to vehicle_id;

alter table eventhub.event
    drop constraint if exists event_vehicle_entity_id_fkey;

alter table eventhub.event
    add constraint fk_event_vehicle
        foreign key (vehicle_id)
        references eventhub.vehicle(id);

drop index if exists eventhub.idx_event_vehicle_time;

create index idx_event_vehicle_time
    on eventhub.event(vehicle_id, occurred_at desc)
    where vehicle_id is not null;

alter table eventhub.event
    drop constraint if exists chk_event_driver_or_vehicle_ref;

alter table eventhub.event
    add constraint chk_event_driver_or_vehicle_ref
        check (
            driver_entity_id is not null
            or vehicle_id is not null
        );
