-- Add explicit owner/co-GM management roles for each Telegram group.

INSERT INTO players (telegram_id, display_name)
SELECT DISTINCT gg.gm_telegram_id,
       'GM ' || gg.gm_telegram_id::text
FROM game_groups gg
ON CONFLICT (telegram_id) DO NOTHING;

CREATE TABLE group_managers (
    id                  UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    group_id            UUID NOT NULL REFERENCES game_groups(id) ON DELETE CASCADE,
    player_id           UUID NOT NULL REFERENCES players(id) ON DELETE CASCADE,
    role                VARCHAR(50) NOT NULL CHECK (role IN ('Owner', 'CoGm')),
    added_by_player_id  UUID REFERENCES players(id) ON DELETE SET NULL,
    created_at          TIMESTAMPTZ NOT NULL DEFAULT now(),
    UNIQUE (group_id, player_id)
);

INSERT INTO group_managers (group_id, player_id, role)
SELECT gg.id, p.id, 'Owner'
FROM game_groups gg
JOIN players p ON p.telegram_id = gg.gm_telegram_id
ON CONFLICT (group_id, player_id) DO NOTHING;

CREATE INDEX ix_group_managers_group_role ON group_managers (group_id, role);
CREATE INDEX ix_group_managers_player ON group_managers (player_id);
