-- VILERIA — schéma initial
CREATE EXTENSION IF NOT EXISTS pgcrypto;

CREATE TABLE users (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  username text NOT NULL,
  username_lower text GENERATED ALWAYS AS (lower(username)) STORED UNIQUE,
  display_name text NOT NULL,
  email text,
  password_hash text NOT NULL,
  role text NOT NULL DEFAULT 'joueur' CHECK (role IN ('joueur', 'admin')),
  disabled boolean NOT NULL DEFAULT false,
  created_at timestamptz NOT NULL DEFAULT now(),
  last_login_at timestamptz
);

CREATE TABLE sessions (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  token_hash text NOT NULL UNIQUE,
  created_at timestamptz NOT NULL DEFAULT now(),
  last_seen_at timestamptz NOT NULL DEFAULT now(),
  expires_at timestamptz NOT NULL,
  revoked_at timestamptz,
  user_agent text,
  ip text
);
CREATE INDEX sessions_user ON sessions(user_id);

CREATE TABLE password_resets (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  token_hash text NOT NULL UNIQUE,
  created_by uuid REFERENCES users(id),
  created_at timestamptz NOT NULL DEFAULT now(),
  expires_at timestamptz NOT NULL,
  used_at timestamptz
);

CREATE TABLE login_attempts (
  id bigserial PRIMARY KEY,
  username_lower text NOT NULL,
  ip text,
  success boolean NOT NULL,
  at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX login_attempts_user ON login_attempts(username_lower, at);
CREATE INDEX login_attempts_ip ON login_attempts(ip, at);

CREATE TABLE audit_log (
  id bigserial PRIMARY KEY,
  at timestamptz NOT NULL DEFAULT now(),
  user_id uuid REFERENCES users(id) ON DELETE SET NULL,
  action text NOT NULL,
  details jsonb NOT NULL DEFAULT '{}',
  ip text
);
CREATE INDEX audit_at ON audit_log(at DESC);

-- Jeux de règles et cartes versionnés : une version publiée n'est jamais modifiée.
CREATE TABLE rulesets (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  version int NOT NULL UNIQUE,
  label text NOT NULL,
  status text NOT NULL CHECK (status IN ('officiel', 'provisoire', 'test')),
  data jsonb NOT NULL,
  notes text,
  is_default boolean NOT NULL DEFAULT false,
  created_by uuid REFERENCES users(id),
  created_at timestamptz NOT NULL DEFAULT now()
);
CREATE UNIQUE INDEX rulesets_one_default ON rulesets(is_default) WHERE is_default;

CREATE TABLE maps (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  version int NOT NULL UNIQUE,
  name text NOT NULL,
  status text NOT NULL CHECK (status IN ('officielle', 'demonstration', 'brouillon')),
  data jsonb NOT NULL,
  is_default boolean NOT NULL DEFAULT false,
  created_by uuid REFERENCES users(id),
  created_at timestamptz NOT NULL DEFAULT now()
);
CREATE UNIQUE INDEX maps_one_default ON maps(is_default) WHERE is_default;

CREATE TABLE games (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  code text NOT NULL UNIQUE,
  name text NOT NULL,
  owner_id uuid NOT NULL REFERENCES users(id),
  status text NOT NULL DEFAULT 'lobby' CHECK (status IN ('lobby', 'active', 'paused', 'finished', 'cancelled')),
  max_players int NOT NULL CHECK (max_players BETWEEN 3 AND 6),
  ruleset_id uuid NOT NULL REFERENCES rulesets(id),
  map_id uuid NOT NULL REFERENCES maps(id),
  options jsonb NOT NULL DEFAULT '{}',
  state jsonb,
  state_version int NOT NULL DEFAULT 0,
  pause_reason text,
  turn_deadline timestamptz,
  created_at timestamptz NOT NULL DEFAULT now(),
  started_at timestamptz,
  finished_at timestamptz,
  winner_id uuid REFERENCES users(id),
  victory jsonb,
  is_test boolean NOT NULL DEFAULT false
);

CREATE TABLE game_players (
  game_id uuid NOT NULL REFERENCES games(id) ON DELETE CASCADE,
  user_id uuid NOT NULL REFERENCES users(id),
  faction text CHECK (faction IN ('skoldaris', 'corbiens', 'hesperides', 'taldars', 'velmoreens', 'visiliens')),
  ready boolean NOT NULL DEFAULT false,
  result text CHECK (result IN ('victoire', 'defaite', 'abandon')),
  joined_at timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (game_id, user_id)
);
CREATE UNIQUE INDEX game_players_faction ON game_players(game_id, faction) WHERE faction IS NOT NULL;

-- Journal des actions : rejouable, et protège des doubles exécutions (client_action_id unique).
CREATE TABLE game_actions (
  id bigserial PRIMARY KEY,
  game_id uuid NOT NULL REFERENCES games(id) ON DELETE CASCADE,
  seq int NOT NULL,
  user_id uuid NOT NULL REFERENCES users(id),
  client_action_id text NOT NULL,
  action jsonb NOT NULL,
  events jsonb NOT NULL DEFAULT '[]',
  created_at timestamptz NOT NULL DEFAULT now(),
  UNIQUE (game_id, seq),
  UNIQUE (game_id, user_id, client_action_id)
);

CREATE TABLE chat_messages (
  id bigserial PRIMARY KEY,
  game_id uuid NOT NULL REFERENCES games(id) ON DELETE CASCADE,
  sender_id uuid NOT NULL REFERENCES users(id),
  recipient_id uuid REFERENCES users(id),
  body text NOT NULL CHECK (char_length(body) BETWEEN 1 AND 500),
  created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX chat_game ON chat_messages(game_id, created_at);
