CREATE EXTENSION IF NOT EXISTS "pgcrypto";

CREATE TABLE IF NOT EXISTS users (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    username TEXT UNIQUE NOT NULL,
    client_salt TEXT NOT NULL,
    encrypted_master_key TEXT NOT NULL,
    hashed_auth_key TEXT NOT NULL,
    public_identity_key TEXT NOT NULL,
    public_signing_key TEXT NOT NULL,
    encrypted_private_keys TEXT NOT NULL, -- Added this column
    is_admin BOOLEAN DEFAULT FALSE,
    created_at TIMESTAMP DEFAULT NOW()
);

CREATE TABLE IF NOT EXISTS channels (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    name TEXT UNIQUE NOT NULL,
    type TEXT DEFAULT 'text',
    created_at TIMESTAMP DEFAULT NOW()
);

CREATE TABLE IF NOT EXISTS roles (
    id SERIAL PRIMARY KEY,
    name TEXT NOT NULL,
    permissions JSONB
);

CREATE TABLE IF NOT EXISTS channel_keys (
    channel_id UUID NOT NULL,
    user_id UUID NOT NULL,
    encrypted_key_bundle TEXT NOT NULL,
    key_version INTEGER DEFAULT 1,
    PRIMARY KEY (channel_id, user_id)
);

CREATE TABLE IF NOT EXISTS messages (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    channel_id UUID NOT NULL,
    sender_id UUID NOT NULL,
    ciphertext TEXT NOT NULL,
    nonce TEXT NOT NULL,
    signature TEXT NOT NULL,
    key_version INTEGER NOT NULL,
    created_at TIMESTAMP DEFAULT NOW()
);
