create extension if not exists timescaledb;

create table if not exists eventhub.event_source_record (
    source_record_key_hash text primary key,
    event_occurred_at timestamptz not null,
    event_id uuid not null,
    created_at timestamptz not null default now()
);

insert into eventhub.event_source_record(source_record_key_hash, event_occurred_at, event_id)
select event.source_record_key_hash, event.occurred_at, event.id
from eventhub.event
on conflict (source_record_key_hash) do nothing;

alter table eventhub.event_detail
    drop constraint if exists fk_event_detail_event;

alter table eventhub.event_source_record
    drop constraint if exists fk_event_source_record_event;

drop index if exists eventhub.ux_event_source_record;

do $$
begin
    if not exists (
        select 1
        from timescaledb_information.hypertables
        where hypertable_schema = 'eventhub'
          and hypertable_name = 'event'
    ) then
        perform create_hypertable(
            'eventhub.event',
            'occurred_at',
            chunk_time_interval => interval '7 days',
            migrate_data => true
        );
    end if;
end $$;

alter table eventhub.event_detail
    add constraint fk_event_detail_event foreign key (event_occurred_at, event_id)
        references eventhub.event(occurred_at, id)
        on delete cascade;

alter table eventhub.event_source_record
    add constraint fk_event_source_record_event foreign key (event_occurred_at, event_id)
        references eventhub.event(occurred_at, id)
        on delete cascade
        deferrable initially deferred;

create index if not exists idx_event_source_record_event
    on eventhub.event_source_record(event_occurred_at, event_id);
