-- Migration: Add routing columns and performance indexes
-- This enables multi-domain routing with <5ms lookup performance

-- Add route column and SEO fields to pages
ALTER TABLE pages
ADD COLUMN IF NOT EXISTS route VARCHAR(512),
ADD COLUMN IF NOT EXISTS status VARCHAR(50) DEFAULT 'draft',
ADD COLUMN IF NOT EXISTS meta_title VARCHAR(255),
ADD COLUMN IF NOT EXISTS meta_description VARCHAR(512),
ADD COLUMN IF NOT EXISTS seo_data JSONB DEFAULT '{}',
ADD COLUMN IF NOT EXISTS published_at TIMESTAMPTZ;

-- Migrate existing slugs to routes
UPDATE pages SET route = '/' || slug WHERE route IS NULL;

-- Make route required
ALTER TABLE pages ALTER COLUMN route SET NOT NULL;

-- ⚡ CRITICAL: Performance indexes for <5ms routing
CREATE INDEX IF NOT EXISTS idx_pages_site_route ON pages (site_id, route);

CREATE INDEX IF NOT EXISTS idx_sites_domain_active ON sites (domain)
WHERE
    status = 'active';

-- Unique constraint per site
ALTER TABLE pages
ADD CONSTRAINT unique_site_route UNIQUE (site_id, route);

-- Add status index for published pages
CREATE INDEX IF NOT EXISTS idx_pages_status ON pages (status)
WHERE
    status = 'published';

-- Add route index
CREATE INDEX IF NOT EXISTS idx_pages_route ON pages (route);

-- Same SEO fields for posts
ALTER TABLE posts
ADD COLUMN IF NOT EXISTS seo_data JSONB DEFAULT '{}';

-- Performance index for posts
CREATE INDEX IF NOT EXISTS idx_posts_site_slug ON posts (site_id, slug);

CREATE INDEX IF NOT EXISTS idx_posts_status ON posts (status)
WHERE
    status = 'published';

-- Success message
DO $$ BEGIN RAISE NOTICE '✅ Multi-domain routing migration complete - Indexes created for <5ms performance';

END $$;