create table if not exists tribe_changes
(
    id           bigint generated by default as identity
        primary key,
    player_id    bigint                                             not null,
    new_tribe_id bigint,
    old_tribe_id bigint,
    server_key   varchar(100)                                       not null
        references servers,
    created_at   timestamp with time zone default CURRENT_TIMESTAMP not null,
    foreign key (player_id, server_key) references players
);

create index if not exists tribe_changes_server_key_player_id_idx
    on tribe_changes (server_key, player_id);

create unique index if not exists tribe_changes_hash_key
    on tribe_changes (hash_record_extended(
                              ROW (player_id, new_tribe_id, old_tribe_id, server_key, date_trunc('hours'::text, (created_at AT TIME ZONE 'UTC'::text))),
                              0::bigint));

create index if not exists tribe_changes_server_key_new_tribe_id_idx
    on tribe_changes (server_key, new_tribe_id);

create index if not exists tribe_changes_server_key_old_tribe_id_idx
    on tribe_changes (server_key, old_tribe_id);
