-- +goose Up
CREATE TABLE IF NOT EXISTS work_types (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL UNIQUE,
    created_at INTEGER NOT NULL DEFAULT (unixepoch())
);

INSERT OR IGNORE INTO work_types (id, name) VALUES (1, 'onsite');
INSERT OR IGNORE INTO work_types (id, name) VALUES (2, 'remote');

CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    chat_id INTEGER NOT NULL UNIQUE,
    timezone TEXT NOT NULL DEFAULT 'Asia/Tehran',
    is_active INTEGER NOT NULL DEFAULT 1,
    report_enabled INTEGER NOT NULL DEFAULT 1,
    report_time TEXT NOT NULL DEFAULT '23:00',
    last_report_date TEXT DEFAULT NULL,
    export_accent TEXT NOT NULL DEFAULT 'ocean'
        CHECK (export_accent IN ('ocean', 'beach', 'rose', 'catppuccin')),
    calendar TEXT NOT NULL DEFAULT 'gregorian'
        CHECK (calendar IN ('gregorian', 'jalali', 'hijri')),
    created_at INTEGER NOT NULL DEFAULT (unixepoch()),
    updated_at INTEGER NOT NULL DEFAULT (unixepoch())
);

CREATE TABLE IF NOT EXISTS days (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id INTEGER NOT NULL REFERENCES users(id),
    date TEXT NOT NULL CHECK (date = strftime('%Y-%m-%d', date)),
    is_day_off INTEGER NOT NULL DEFAULT 0,
    day_off_reason TEXT NOT NULL DEFAULT '',
    current_work_type_id INTEGER NOT NULL DEFAULT 1 REFERENCES work_types(id),
    min_break_threshold INTEGER NOT NULL DEFAULT 300,
    created_at INTEGER NOT NULL DEFAULT (unixepoch()),
    updated_at INTEGER NOT NULL DEFAULT (unixepoch()),
    UNIQUE(user_id, date)
);

CREATE TABLE IF NOT EXISTS events (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id INTEGER NOT NULL REFERENCES users(id),
    day_id INTEGER NOT NULL REFERENCES days(id),
    event_type TEXT NOT NULL CHECK (event_type IN ('in', 'out')),
    work_type_id INTEGER REFERENCES work_types(id),
    occurred_at INTEGER NOT NULL CHECK (occurred_at > 0),
    note TEXT NOT NULL DEFAULT '',
    created_at INTEGER NOT NULL DEFAULT (unixepoch())
);

CREATE INDEX IF NOT EXISTS idx_events_user_day ON events(user_id, day_id);
CREATE INDEX IF NOT EXISTS idx_events_user_occurred ON events(user_id, occurred_at);
CREATE INDEX IF NOT EXISTS idx_days_user_date ON days(user_id, date);

-- +goose Down
DROP TABLE IF EXISTS events;
DROP TABLE IF EXISTS days;
DROP TABLE IF EXISTS users;
DROP TABLE IF EXISTS work_types;
