CREATE EXTENSION IF NOT EXISTS pgcrypto;

CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    username VARCHAR(255) UNIQUE NOT NULL,
    password_hash TEXT NOT NULL,
    permissions_mask TEXT NOT NULL DEFAULT '0',
    created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE permissions (
    id SERIAL PRIMARY KEY,
    name VARCHAR(255) UNIQUE NOT NULL,
    bit_value TEXT UNIQUE NOT NULL,
    description TEXT
);

CREATE TABLE queries (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    identifier VARCHAR(255) UNIQUE NOT NULL,
    sql_template TEXT NOT NULL,
    description TEXT,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE blacklist (
    id SERIAL PRIMARY KEY,
    pattern VARCHAR(500) NOT NULL,
    method VARCHAR(10),
    reason TEXT,
    active BOOLEAN NOT NULL DEFAULT true,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- Seed permissions
INSERT INTO permissions (name, bit_value, description) VALUES
    ('READ',        '1',  'Can read via CRUD endpoints'),
    ('WRITE',       '2',  'Can insert/update via CRUD'),
    ('DELETE',      '4',  'Can delete via CRUD'),
    ('ADMIN_QUERY', '8',  'Can manage query registry'),
    ('ADMIN_CACHE', '16', 'Can manage cache'),
    ('SUPER_ADMIN', '32', 'Full access');

-- Seed blacklist (users and permissions tables are admin-only)
INSERT INTO blacklist (pattern, method, reason, active) VALUES
    ('/api/users/**',       NULL, 'admin-only table', true),
    ('/api/permissions/**', NULL, 'admin-only table', true);
