-- I18N Database Initialization

CREATE SCHEMA IF NOT EXISTS i18n;

-- Translations table
CREATE TABLE IF NOT EXISTS i18n.translations (
    id SERIAL PRIMARY KEY,
    key VARCHAR(255) NOT NULL,
    namespace VARCHAR(100) NOT NULL DEFAULT 'common',
    locale VARCHAR(10) NOT NULL,
    source_text TEXT NOT NULL,
    translated_text TEXT NOT NULL,
    quality_score DECIMAL(3, 2) DEFAULT 0.00,
    provider VARCHAR(50),
    from_cache BOOLEAN DEFAULT FALSE,
    from_static BOOLEAN DEFAULT FALSE,
    created_at TIMESTAMPTZ DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW(),
    UNIQUE(key, namespace, locale)
);

-- Glossary table
CREATE TABLE IF NOT EXISTS i18n.glossary (
    id SERIAL PRIMARY KEY,
    source VARCHAR(255) NOT NULL,
    category VARCHAR(100) NOT NULL DEFAULT 'general',
    translations JSONB NOT NULL DEFAULT '{}',
    created_at TIMESTAMPTZ DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW(),
    UNIQUE(source, category)
);

-- Locales table
CREATE TABLE IF NOT EXISTS i18n.locales (
    code VARCHAR(10) PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    native_name VARCHAR(100) NOT NULL,
    flag VARCHAR(10),
    rtl BOOLEAN DEFAULT FALSE,
    enabled BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMPTZ DEFAULT NOW()
);

-- Insert default locales
INSERT INTO i18n.locales (code, name, native_name, flag, rtl) VALUES
    ('en', 'English', 'English', '🇺🇸', false),
    ('es', 'Spanish', 'Español', '🇪🇸', false),
    ('fr', 'French', 'Français', '🇫🇷', false),
    ('de', 'German', 'Deutsch', '🇩🇪', false),
    ('ja', 'Japanese', '日本語', '🇯🇵', false),
    ('ko', 'Korean', '한국어', '🇰🇷', false),
    ('zh', 'Chinese', '中文', '🇨🇳', false),
    ('ar', 'Arabic', 'العربية', '🇸🇦', true),
    ('pt', 'Portuguese', 'Português', '🇵🇹', false),
    ('ru', 'Russian', 'Русский', '🇷🇺', false)
ON CONFLICT (code) DO NOTHING;

-- Indexes
CREATE INDEX IF NOT EXISTS idx_translations_key ON i18n.translations(key, locale);
CREATE INDEX IF NOT EXISTS idx_translations_namespace ON i18n.translations(namespace);
CREATE INDEX IF NOT EXISTS idx_glossary_category ON i18n.glossary(category);

-- Permissions
GRANT ALL PRIVILEGES ON SCHEMA i18n TO lilith;
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA i18n TO lilith;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA i18n TO lilith;

DO $$ BEGIN RAISE NOTICE 'I18N database initialized'; END $$;
