CREATE TABLE IF NOT EXISTS users (
    id UUID NOT NULL PRIMARY KEY,
    uid TEXT UNIQUE NOT NULL,
    email TEXT NOT NULL
);
CREATE INDEX ON users (uid);

CREATE TABLE IF NOT EXISTS csrf_tokens (
    id UUID NOT NULL PRIMARY KEY,
    user_id UUID REFERENCES users(id),
    created_at TIMESTAMPTZ NOT NULL
);
CREATE INDEX ON csrf_tokens (created_at);

CREATE TABLE teams (
    id UUID NOT NULL PRIMARY KEY,
    name TEXT NOT NULL
);

CREATE TABLE team_memberships (
    team_id UUID NOT NULL REFERENCES teams(id),
    user_id UUID NOT NULL REFERENCES users(id),
    roles TEXT[] NOT NULL DEFAULT '{}',
    PRIMARY KEY (team_id, user_id)
);
CREATE INDEX ON team_memberships (team_id);
CREATE INDEX ON team_memberships (user_id);

CREATE TABLE api_keys (
    id UUID NOT NULL PRIMARY KEY,
    team_id UUID NOT NULL REFERENCES teams(id),
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    last_used_at TIMESTAMPTZ
);
CREATE INDEX ON api_Keys (team_id);

CREATE TABLE projects (
    id UUID NOT NULL PRIMARY KEY,
    team_id UUID NOT NULL REFERENCES teams(id),
    name TEXT NOT NULL,
    UNIQUE (team_id, name)
);
CREATE INDEX ON projects(team_id);
