-- Official account AI posting configurations
CREATE TABLE IF NOT EXISTS official_account_configs (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    profile_id UUID NOT NULL REFERENCES public.profiles(id) ON DELETE CASCADE,
    account_type TEXT NOT NULL DEFAULT 'general', -- 'general', 'news', 'community', etc.
    enabled BOOLEAN NOT NULL DEFAULT false,

    -- AI config
    model_id TEXT NOT NULL DEFAULT 'google/gemini-2.0-flash-001',
    system_prompt TEXT NOT NULL DEFAULT '',
    temperature DOUBLE PRECISION NOT NULL DEFAULT 0.7,
    max_tokens INTEGER NOT NULL DEFAULT 500,

    -- Posting config
    post_interval_minutes INTEGER NOT NULL DEFAULT 60,
    max_posts_per_day INTEGER NOT NULL DEFAULT 24,
    posts_today INTEGER NOT NULL DEFAULT 0,
    posts_today_reset_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    last_posted_at TIMESTAMPTZ,

    -- News-specific config (only for account_type = 'news')
    news_sources JSONB NOT NULL DEFAULT '[]'::jsonb,  -- array of {name, rss_url, enabled}
    last_fetched_at TIMESTAMPTZ,

    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),

    CONSTRAINT unique_profile_config UNIQUE (profile_id)
);

CREATE INDEX IF NOT EXISTS idx_oac_profile ON official_account_configs(profile_id);
CREATE INDEX IF NOT EXISTS idx_oac_enabled ON official_account_configs(enabled) WHERE enabled = true;

-- Track which news articles have already been posted to avoid duplicates
CREATE TABLE IF NOT EXISTS official_account_posted_articles (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    config_id UUID NOT NULL REFERENCES official_account_configs(id) ON DELETE CASCADE,
    article_url TEXT NOT NULL,
    article_title TEXT NOT NULL DEFAULT '',
    source_name TEXT NOT NULL DEFAULT '',
    posted_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    post_id UUID REFERENCES public.posts(id) ON DELETE SET NULL,

    CONSTRAINT unique_article_per_config UNIQUE (config_id, article_url)
);

CREATE INDEX IF NOT EXISTS idx_oapa_config ON official_account_posted_articles(config_id);
CREATE INDEX IF NOT EXISTS idx_oapa_url ON official_account_posted_articles(article_url);
