-- 008_drivers_clans.sql — drivers and clans.
--
-- A driver is a person who can join races. Each driver has a unique
-- 3-letter nickname (A-Z, uppercase, exactly 3 characters) and an
-- optional avatar URL. Drivers can belong to at most one clan.
--
-- A clan is a team that groups drivers. Each clan has a unique 3-letter
-- tag (same rules as the driver nickname) and an optional avatar URL.
--
-- Constraints:
--   * nickname  is exactly 3 uppercase ASCII letters and unique.
--   * tag       is exactly 3 uppercase ASCII letters and unique.
--   * driver.clan_id is a soft FK (nullable); ON DELETE SET NULL.

CREATE TABLE IF NOT EXISTS clans (
    id          TEXT PRIMARY KEY,
    tag         TEXT NOT NULL UNIQUE,
    name        TEXT NOT NULL,
    avatar_url  TEXT NOT NULL DEFAULT '',
    created_ms  BIGINT NOT NULL,
    updated_ms  BIGINT NOT NULL
);

CREATE INDEX IF NOT EXISTS clans_tag_idx ON clans (tag);

CREATE TABLE IF NOT EXISTS drivers (
    id          TEXT PRIMARY KEY,
    nickname    TEXT NOT NULL UNIQUE,
    name        TEXT NOT NULL,
    avatar_url  TEXT NOT NULL DEFAULT '',
    clan_id     TEXT REFERENCES clans(id) ON DELETE SET NULL,
    created_ms  BIGINT NOT NULL,
    updated_ms  BIGINT NOT NULL
);

CREATE INDEX IF NOT EXISTS drivers_nickname_idx ON drivers (nickname);
CREATE INDEX IF NOT EXISTS drivers_clan_idx     ON drivers (clan_id);
