-- schema.sql
CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    username TEXT UNIQUE NOT NULL,
    email TEXT UNIQUE NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    password TEXT NOT NULL,
    status INTEGER DEFAULT 0
);

CREATE TABLE IF NOT EXISTS sessions (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id INTEGER NOT NULL,
    session_id TEXT UNIQUE NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id)
);

CREATE TABLE IF NOT EXISTS tasks (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id INTEGER NOT NULL,
    task TEXT UNIQUE NOT NULL,
    description TEXT,
    status TEXT,
    external_url TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id)
);

CREATE TABLE IF NOT EXISTS permissions (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id INTEGER NOT NULL,
    permission TEXT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id)
);

CREATE TABLE IF NOT EXISTS accounts (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    account_id INTEGER NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE IF NOT EXISTS user_accounts (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id INTEGER NOT NULL,
    account_id INTEGER NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
    FOREIGN KEY (account_id) REFERENCES accounts(id) ON DELETE CASCADE,

    UNIQUE (user_id, account_id)
);

CREATE TABLE IF NOT EXISTS pageviews (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    account_id INTEGER NOT NULL,
    page TEXT NOT NULL,
    user_agent TEXT,
    referrer TEXT,
    ip TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (account_id) REFERENCES accounts(id) ON DELETE CASCADE
);

CREATE INDEX IF NOT EXISTS idx_pageviews_account_id
ON pageviews(account_id);

CREATE INDEX IF NOT EXISTS idx_pageviews_created_at
ON pageviews(created_at);

CREATE INDEX IF NOT EXISTS idx_pageviews_account_time
ON pageviews(account_id, created_at);

INSERT INTO users (username, email, password) VALUES 
    ('bender', 'dan@danchadwickdesign.com', 'aa7101dc6e2fe541ac5a44352c24d15052723b70ceecd5fc6d7fe71d0721c9aa');

INSERT INTO permissions (user_id, permission) VALUES 
    (1, 'admin');

INSERT INTO accounts (account_id) VALUES ("3116a529b262b9f3cc08a4ba87d5d833");

INSERT INTO user_accounts (user_id, account_id) VALUES (1,"3116a529b262b9f3cc08a4ba87d5d833");

INSERT INTO tasks (user_id, task, description, status, external_url) VALUES 
    (1, 'Buy milk', 'this task requires you to go to the store and buy milk.', 'pending', 'https://www.google.com');

INSERT INTO tasks (user_id, task, description, status, external_url) VALUES 
    (1, 'Buy eggs', 'this task requires you to go to the store and buy eggs.', 'pending', 'https://www.google.com');
