package migrations

import (
	"context"

	"github.com/uptrace/bun"
)

func init() {
	migrations.MustRegister(func(ctx context.Context, db *bun.DB) error {
		_, err := db.ExecContext(ctx, `
create table if not exists tribe_changes
(
    ?ID_COL,
    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 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);
`)
		return err
	}, func(ctx context.Context, db *bun.DB) error {
		_, err := db.ExecContext(ctx, "drop table if exists tribe_changes cascade;")
		return err
	})
}
