-- JIGAIDO Database Schema

CREATE TABLE IF NOT EXISTS groups (
    id              INTEGER PRIMARY KEY AUTOINCREMENT,
    telegram_chat_id INTEGER UNIQUE NOT NULL,
    creator_user_id  INTEGER NOT NULL,
    created_at       INTEGER NOT NULL DEFAULT (unixepoch())
);

CREATE TABLE IF NOT EXISTS group_admins (
    group_id  INTEGER REFERENCES groups(id) ON DELETE CASCADE,
    user_id   INTEGER NOT NULL,
    PRIMARY KEY (group_id, user_id)
);

CREATE TABLE IF NOT EXISTS users (
    id               INTEGER PRIMARY KEY AUTOINCREMENT,
    telegram_user_id  INTEGER UNIQUE NOT NULL,
    username          TEXT,
    created_at        INTEGER NOT NULL DEFAULT (unixepoch())
);

CREATE TABLE IF NOT EXISTS bounties (
    id                   INTEGER PRIMARY KEY AUTOINCREMENT,
    group_id              INTEGER REFERENCES groups(id) ON DELETE CASCADE,
    created_by_user_id    INTEGER REFERENCES users(id),
    informed_by_username  TEXT NOT NULL,
    text                  TEXT,
    link                  TEXT,
    due_date_ts           INTEGER,
    created_at            INTEGER NOT NULL DEFAULT (unixepoch()),
    UNIQUE(group_id, link)
);

CREATE TABLE IF NOT EXISTS user_bounty_tracking (
    id         INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id    INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    bounty_id  INTEGER NOT NULL REFERENCES bounties(id) ON DELETE CASCADE,
    added_at   INTEGER NOT NULL DEFAULT (unixepoch()),
    UNIQUE(user_id, bounty_id)
);

CREATE TABLE IF NOT EXISTS reminder_log (
    id          INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id     INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    bounty_id   INTEGER NOT NULL REFERENCES bounties(id) ON DELETE CASCADE,
    reminded_at INTEGER NOT NULL DEFAULT (unixepoch()),
    UNIQUE(user_id, bounty_id)
);
