-- ============================================================
-- Migration: article_status_scheduling
-- Timestamp: 20260321080000
-- Adds: pending status support + scheduled_at column to both article tables
-- ============================================================

-- 1. Add scheduled_at to wp_imported_posts
ALTER TABLE public.wp_imported_posts
  ADD COLUMN IF NOT EXISTS scheduled_at TIMESTAMPTZ,
  ADD COLUMN IF NOT EXISTS submitted_for_review_at TIMESTAMPTZ;

-- 2. Add scheduled_at to native_articles
ALTER TABLE public.native_articles
  ADD COLUMN IF NOT EXISTS scheduled_at TIMESTAMPTZ,
  ADD COLUMN IF NOT EXISTS submitted_for_review_at TIMESTAMPTZ;

-- 3. Add status index for pending on both tables
CREATE INDEX IF NOT EXISTS idx_wp_imported_posts_status ON public.wp_imported_posts(status);
CREATE INDEX IF NOT EXISTS idx_wp_imported_posts_scheduled_at ON public.wp_imported_posts(scheduled_at) WHERE scheduled_at IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_native_articles_scheduled_at ON public.native_articles(scheduled_at) WHERE scheduled_at IS NOT NULL;

-- 4. Function to auto-publish scheduled articles (called via cron or on-demand)
CREATE OR REPLACE FUNCTION public.publish_scheduled_articles()
RETURNS INTEGER
LANGUAGE plpgsql
AS $$
DECLARE
  published_count INTEGER := 0;
  native_count    INTEGER := 0;
BEGIN
  -- Publish scheduled wp_imported_posts
  UPDATE public.wp_imported_posts
  SET status = 'published', scheduled_at = NULL, updated_at = CURRENT_TIMESTAMP
  WHERE status = 'draft'
    AND scheduled_at IS NOT NULL
    AND scheduled_at <= CURRENT_TIMESTAMP;
  GET DIAGNOSTICS published_count = ROW_COUNT;

  -- Publish scheduled native_articles
  UPDATE public.native_articles
  SET status = 'published', scheduled_at = NULL, published_at = CURRENT_TIMESTAMP, updated_at = CURRENT_TIMESTAMP
  WHERE status = 'draft'
    AND scheduled_at IS NOT NULL
    AND scheduled_at <= CURRENT_TIMESTAMP;
  GET DIAGNOSTICS native_count = ROW_COUNT;

  published_count := published_count + native_count;

  RETURN published_count;
END;
$$;
