-- +goose Up
CREATE TABLE users (
    id TEXT PRIMARY KEY,
    username TEXT UNIQUE NOT NULL,
    password_hash TEXT NOT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX idx_users_username ON users(username);

CREATE TABLE games (
    id TEXT PRIMARY KEY,
    board TEXT NOT NULL,
    current_turn INTEGER NOT NULL DEFAULT 1,
    status INTEGER NOT NULL DEFAULT 0,
    winner_user_id TEXT,
    winning_cells TEXT,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE game_players (
    game_id TEXT NOT NULL,
    user_id TEXT,
    guest_player_id TEXT,
    nickname TEXT NOT NULL,
    color INTEGER NOT NULL,
    slot INTEGER NOT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (game_id, slot),
    FOREIGN KEY (game_id) REFERENCES games(id) ON DELETE CASCADE,
    FOREIGN KEY (user_id) REFERENCES users(id),
    CHECK (user_id IS NOT NULL OR guest_player_id IS NOT NULL)
);
CREATE INDEX idx_game_players_user ON game_players(user_id);
CREATE INDEX idx_game_players_guest ON game_players(guest_player_id);

-- +goose Down
DROP TABLE IF EXISTS game_players;
DROP TABLE IF EXISTS games;
DROP TABLE IF EXISTS users;
