CREATE TABLE IF NOT EXISTS users (
    sub TEXT PRIMARY KEY,
    email TEXT NOT NULL DEFAULT '',
    name TEXT NOT NULL DEFAULT '',
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE TABLE IF NOT EXISTS skills (
    id BIGSERIAL PRIMARY KEY,
    owner_sub TEXT NOT NULL REFERENCES users(sub) ON DELETE CASCADE,
    title TEXT NOT NULL,
    description TEXT NOT NULL,
    price_cents INTEGER NOT NULL CHECK (price_cents >= 0),
    file_path TEXT NOT NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE TABLE IF NOT EXISTS purchases (
    id BIGSERIAL PRIMARY KEY,
    buyer_sub TEXT NOT NULL REFERENCES users(sub) ON DELETE CASCADE,
    skill_id BIGINT NOT NULL REFERENCES skills(id) ON DELETE CASCADE,
    purchased_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    UNIQUE (buyer_sub, skill_id)
);

CREATE INDEX IF NOT EXISTS idx_skills_owner_sub ON skills(owner_sub);
CREATE INDEX IF NOT EXISTS idx_purchases_buyer_sub ON purchases(buyer_sub);
CREATE INDEX IF NOT EXISTS idx_purchases_skill_id ON purchases(skill_id);

