-- ============================================
-- AegisOne MAX Bot — Database Schema
-- ============================================
-- Run this to set up all bot tables.
-- Assumes database 'aegisone' already exists.

-- ============================================
-- CLEANUP: Drop ALL old bot tables before recreating
-- ============================================
DROP TABLE IF EXISTS bot_1c_sync_log CASCADE;
DROP TABLE IF EXISTS bot_ticket_messages CASCADE;
DROP TABLE IF EXISTS bot_ticket_statuses CASCADE;
DROP TABLE IF EXISTS bot_tickets CASCADE;
DROP TABLE IF EXISTS bot_messages CASCADE;
DROP TABLE IF EXISTS bot_conversations CASCADE;
DROP TABLE IF EXISTS bot_knowledge_base CASCADE;
DROP TABLE IF EXISTS bot_categories CASCADE;
DROP TABLE IF EXISTS bot_users CASCADE;
DROP TABLE IF EXISTS bot_consent_logs CASCADE;
DROP TABLE IF EXISTS bot_features CASCADE;
DROP TABLE IF EXISTS bot_settings CASCADE;
DROP TABLE IF EXISTS bot_notification_subscriptions CASCADE;
DROP TABLE IF EXISTS bot_notifications CASCADE;
DROP TABLE IF EXISTS bot_risk_questions CASCADE;
DROP TABLE IF EXISTS bot_broadcasts CASCADE;
DROP TABLE IF EXISTS bot_response_templates CASCADE;
DROP TABLE IF EXISTS file_sync_queue CASCADE;

-- 1. BOT SETTINGS
CREATE TABLE IF NOT EXISTS bot_settings (
    id SERIAL PRIMARY KEY,
    key VARCHAR(255) UNIQUE NOT NULL,
    value TEXT,
    created_at TIMESTAMP DEFAULT now(),
    updated_at TIMESTAMP DEFAULT now()
);

-- 2. BOT FEATURES
CREATE TABLE IF NOT EXISTS bot_features (
    id SERIAL PRIMARY KEY,
    key VARCHAR(255) UNIQUE NOT NULL,
    name VARCHAR(255) NOT NULL,
    description TEXT,
    is_enabled BOOLEAN DEFAULT FALSE,
    created_at TIMESTAMP DEFAULT now()
);

-- 3. BOT CATEGORIES (for knowledge base)
CREATE TABLE IF NOT EXISTS bot_categories (
    id SERIAL PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    description TEXT,
    sort_order INTEGER DEFAULT 0,
    created_at TIMESTAMP DEFAULT now()
);

-- 4. BOT KNOWLEDGE BASE (Q&A pairs)
CREATE TABLE IF NOT EXISTS bot_knowledge_base (
    id SERIAL PRIMARY KEY,
    category_id INTEGER REFERENCES bot_categories(id) ON DELETE SET NULL,
    question TEXT NOT NULL,
    answer TEXT,
    keywords TEXT[],
    is_active BOOLEAN DEFAULT TRUE,
    source_url VARCHAR(500),
    sort_order INTEGER DEFAULT 0,
    created_at TIMESTAMP DEFAULT now(),
    updated_at TIMESTAMP DEFAULT now()
);

-- 5. BOT USERS (MAX messenger users)
CREATE TABLE IF NOT EXISTS bot_users (
    id BIGINT PRIMARY KEY,
    first_name VARCHAR(255),
    last_name VARCHAR(255),
    patronymic VARCHAR(255),
    username VARCHAR(255),
    phone VARCHAR(50),
    email VARCHAR(255),
    organization VARCHAR(255),
    address TEXT,
    vcf_raw TEXT,
    contact_hash VARCHAR(255),
    phone_verified BOOLEAN DEFAULT FALSE,
    email_verified BOOLEAN DEFAULT FALSE,
    consent_given BOOLEAN DEFAULT FALSE,
    consent_date TIMESTAMP,
    last_interaction TIMESTAMP,
    total_conversations INTEGER DEFAULT 0,
    total_tickets INTEGER DEFAULT 0,
    created_at TIMESTAMP DEFAULT now(),
    updated_at TIMESTAMP DEFAULT now()
);

-- 6. BOT CONVERSATIONS
CREATE TABLE IF NOT EXISTS bot_conversations (
    id BIGSERIAL PRIMARY KEY,
    user_id BIGINT NOT NULL REFERENCES bot_users(id) ON DELETE CASCADE,
    state VARCHAR(50) DEFAULT 'greeting',
    intent VARCHAR(50),
    inquiry_text TEXT,
    created_at TIMESTAMP DEFAULT now(),
    updated_at TIMESTAMP DEFAULT now()
);

-- 7. BOT MESSAGES
CREATE TABLE IF NOT EXISTS bot_messages (
    id BIGSERIAL PRIMARY KEY,
    conversation_id BIGINT NOT NULL REFERENCES bot_conversations(id) ON DELETE CASCADE,
    direction VARCHAR(10) NOT NULL,
    text TEXT,
    attachment_json TEXT,
    created_at TIMESTAMP DEFAULT now()
);

-- 8. BOT TICKETS (support tickets)
CREATE TABLE IF NOT EXISTS bot_tickets (
    id BIGSERIAL PRIMARY KEY,
    user_id BIGINT NOT NULL REFERENCES bot_users(id) ON DELETE CASCADE,
    title VARCHAR(500),
    description TEXT,
    priority VARCHAR(20) DEFAULT 'normal',
    status VARCHAR(20) DEFAULT 'Новая',
    created_by VARCHAR(100) DEFAULT 'bot',
    assigned_to BIGINT,
    created_at TIMESTAMP DEFAULT now(),
    updated_at TIMESTAMP DEFAULT now()
);

-- 9. BOT TICKET MESSAGES
CREATE TABLE IF NOT EXISTS bot_ticket_messages (
    id BIGSERIAL PRIMARY KEY,
    ticket_id BIGINT NOT NULL REFERENCES bot_tickets(id) ON DELETE CASCADE,
    direction VARCHAR(10) NOT NULL,
    text TEXT,
    created_at TIMESTAMP DEFAULT now()
);

-- 10. BOT TICKET STATUSES (change log)
CREATE TABLE IF NOT EXISTS bot_ticket_statuses (
    id BIGSERIAL PRIMARY KEY,
    ticket_id BIGINT NOT NULL REFERENCES bot_tickets(id) ON DELETE CASCADE,
    old_status VARCHAR(20),
    new_status VARCHAR(20) NOT NULL,
    changed_by VARCHAR(100),
    created_at TIMESTAMP DEFAULT now()
);

-- ============================================
-- CLEANUP: Drop unused tables from old bot
-- ============================================
DROP TABLE IF EXISTS bot_notification_subscriptions CASCADE;
DROP TABLE IF EXISTS bot_notifications CASCADE;
DROP TABLE IF EXISTS bot_risk_questions CASCADE;
DROP TABLE IF EXISTS bot_broadcasts CASCADE;
DROP TABLE IF EXISTS file_sync_queue CASCADE;
DROP TABLE IF EXISTS bot_response_templates CASCADE;

-- 11. BOT PROCESSING LOGS (diagnostics & dialogues page)
CREATE TABLE IF NOT EXISTS bot_processing_logs (
    id BIGSERIAL PRIMARY KEY,
    user_id BIGINT NOT NULL REFERENCES bot_users(id) ON DELETE CASCADE,
    conversation_id BIGINT REFERENCES bot_conversations(id) ON DELETE SET NULL,
    step VARCHAR(50) NOT NULL,
    status VARCHAR(20) DEFAULT 'ok',
    message TEXT,
    detail TEXT,
    created_at TIMESTAMP DEFAULT now()
);

-- ============================================
-- INDEXES
-- ============================================
CREATE INDEX IF NOT EXISTS idx_bot_conversations_user_id ON bot_conversations(user_id);
CREATE INDEX IF NOT EXISTS idx_bot_conversations_state ON bot_conversations(state);
CREATE INDEX IF NOT EXISTS idx_bot_messages_conversation_id ON bot_messages(conversation_id);
CREATE INDEX IF NOT EXISTS idx_bot_tickets_user_id ON bot_tickets(user_id);
CREATE INDEX IF NOT EXISTS idx_bot_tickets_status ON bot_tickets(status);
CREATE INDEX IF NOT EXISTS idx_bot_ticket_messages_ticket_id ON bot_ticket_messages(ticket_id);
CREATE INDEX IF NOT EXISTS idx_bot_knowledge_base_category ON bot_knowledge_base(category_id);
CREATE INDEX IF NOT EXISTS idx_bot_knowledge_base_active ON bot_knowledge_base(is_active);
CREATE INDEX IF NOT EXISTS idx_bot_knowledge_base_keywords ON bot_knowledge_base USING gin(keywords);
