-- Add 1v1 Tic-Tac-Toe challenge system
-- Players can challenge each other via community posts; game state is synced via Supabase Realtime.

-- Add challengeId to community_posts
ALTER TABLE rebreak.community_posts ADD COLUMN IF NOT EXISTS challenge_id UUID;

-- GameChallengeStatus enum
DO $$ BEGIN
    CREATE TYPE rebreak."GameChallengeStatus" AS ENUM ('OPEN', 'ACTIVE', 'FINISHED', 'CANCELLED');
EXCEPTION
    WHEN duplicate_object THEN null;
END $$;

-- game_challenges table
CREATE TABLE IF NOT EXISTS rebreak.game_challenges (
    id             UUID        PRIMARY KEY DEFAULT gen_random_uuid(),
    challenger_id  UUID        NOT NULL,
    challenger_name TEXT       NOT NULL,
    opponent_id    UUID,
    opponent_name  TEXT,
    status         rebreak."GameChallengeStatus" NOT NULL DEFAULT 'OPEN',
    board          TEXT        NOT NULL DEFAULT '---------',
    current_turn   TEXT        NOT NULL DEFAULT 'X',
    winner         TEXT,
    post_id        UUID,
    created_at     TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at     TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX IF NOT EXISTS game_challenges_challenger_idx ON rebreak.game_challenges (challenger_id);
CREATE INDEX IF NOT EXISTS game_challenges_opponent_idx  ON rebreak.game_challenges (opponent_id);
CREATE INDEX IF NOT EXISTS game_challenges_status_idx    ON rebreak.game_challenges (status);

-- Enable Supabase Realtime for live game sync
ALTER PUBLICATION supabase_realtime ADD TABLE rebreak.game_challenges;
