-- SEO Feature Database Initialization

-- Domain configurations
CREATE TABLE IF NOT EXISTS domain_configs (
    id SERIAL PRIMARY KEY,
    domain VARCHAR(255) NOT NULL UNIQUE,
    default_locale VARCHAR(10) NOT NULL DEFAULT 'en',
    supported_locales TEXT[] NOT NULL DEFAULT ARRAY['en'],
    site_name VARCHAR(255) NOT NULL,
    twitter_handle VARCHAR(100),
    default_og_image TEXT,
    auto_generate BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Page configurations
CREATE TABLE IF NOT EXISTS page_configs (
    id SERIAL PRIMARY KEY,
    domain_id INTEGER NOT NULL REFERENCES domain_configs(id) ON DELETE CASCADE,
    path VARCHAR(500) NOT NULL,
    page_type VARCHAR(100) NOT NULL DEFAULT 'page',
    variables JSONB DEFAULT '{}',
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    UNIQUE(domain_id, path)
);

-- Metadata overrides per locale
CREATE TABLE IF NOT EXISTS metadata_overrides (
    id SERIAL PRIMARY KEY,
    page_config_id INTEGER NOT NULL REFERENCES page_configs(id) ON DELETE CASCADE,
    locale VARCHAR(10) NOT NULL,
    title VARCHAR(255),
    description TEXT,
    keywords TEXT[],
    og_title VARCHAR(255),
    og_description TEXT,
    og_image TEXT,
    og_type VARCHAR(50) DEFAULT 'website',
    canonical_url TEXT,
    robots VARCHAR(100) DEFAULT 'index,follow',
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    UNIQUE(page_config_id, locale)
);

-- Generated SEO cache
CREATE TABLE IF NOT EXISTS generated_cache (
    id SERIAL PRIMARY KEY,
    domain VARCHAR(255) NOT NULL,
    path VARCHAR(500) NOT NULL,
    locale VARCHAR(10) NOT NULL,
    metadata JSONB NOT NULL,
    source VARCHAR(50) NOT NULL DEFAULT 'generated',
    truth_validation JSONB,
    generated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    expires_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() + INTERVAL '24 hours',
    UNIQUE(domain, path, locale)
);

-- Indexes
CREATE INDEX IF NOT EXISTS idx_domain_configs_domain ON domain_configs(domain);
CREATE INDEX IF NOT EXISTS idx_page_configs_domain_path ON page_configs(domain_id, path);
CREATE INDEX IF NOT EXISTS idx_generated_cache_lookup ON generated_cache(domain, path, locale);
CREATE INDEX IF NOT EXISTS idx_generated_cache_expiry ON generated_cache(expires_at);
