-- Создание таблиц. Теперь схема версионируется!
CREATE TABLE IF NOT EXISTS users (
    id UUID PRIMARY KEY,
    tg_id BIGINT UNIQUE NOT NULL,
    tg_username VARCHAR(255),
    role VARCHAR(50) NOT NULL DEFAULT 'user',
    balance BIGINT NOT NULL DEFAULT 0,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE TABLE IF NOT EXISTS referrals (
    referrer_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    referred_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    earned_bonus BIGINT NOT NULL DEFAULT 100,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    PRIMARY KEY (referrer_id, referred_id),
    UNIQUE (referred_id)
);

CREATE TABLE IF NOT EXISTS subscriptions (
    user_id UUID PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
    plan_name VARCHAR(50) NOT NULL DEFAULT 'Free',
    expires_at TIMESTAMPTZ,
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE TABLE IF NOT EXISTS plans (
    name VARCHAR(50) PRIMARY KEY,
    price BIGINT NOT NULL,
    is_active BOOLEAN NOT NULL DEFAULT TRUE
);

INSERT INTO plans (name, price) VALUES 
    ('GHOST', 5), ('NETRUNNER', 9), ('MAINFRAME', 20)
ON CONFLICT (name) DO NOTHING;