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,
    game_tickets INT NOT NULL DEFAULT 0,
    has_used_trial BOOLEAN NOT NULL DEFAULT FALSE,
    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), 
    expires_at TIMESTAMPTZ,
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

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

INSERT INTO plans (name, price_usd, price_rub) VALUES 
    ('GHOST', 5, 500), 
    ('NETRUNNER', 9, 900), 
    ('MAINFRAME', 20, 2000)
ON CONFLICT (name) DO NOTHING;