-- Users table for API key authentication
CREATE TABLE IF NOT EXISTS users (
    id            BIGSERIAL PRIMARY KEY,
    username      TEXT NOT NULL UNIQUE,
    display_name  TEXT NOT NULL DEFAULT '',
    role          TEXT NOT NULL DEFAULT 'user',
    api_key       TEXT UNIQUE,
    created_at    TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE UNIQUE INDEX IF NOT EXISTS idx_users_api_key ON users (api_key) WHERE api_key IS NOT NULL;

-- Requests table for media request workflow
CREATE TABLE IF NOT EXISTS requests (
    id                 BIGSERIAL PRIMARY KEY,
    media_id           BIGINT,
    media_type         TEXT NOT NULL DEFAULT '',
    title              TEXT NOT NULL DEFAULT '',
    requested_by       BIGINT NOT NULL REFERENCES users(id),
    status             TEXT NOT NULL DEFAULT 'pending',
    quality_profile_id INTEGER REFERENCES quality_profiles(id),
    root_folder_id     INTEGER REFERENCES root_folders(id),
    notes              TEXT DEFAULT '',
    reviewed_by        BIGINT REFERENCES users(id),
    reviewed_at        TIMESTAMPTZ,
    created_at         TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at         TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_requests_status ON requests (status);
CREATE INDEX IF NOT EXISTS idx_requests_requested_by ON requests (requested_by);
CREATE INDEX IF NOT EXISTS idx_requests_media ON requests (media_id, media_type);
