-- COMPREHENSIVE FIELD RENAME MIGRATION
-- Renames all entity_type, cluster_role, site_entity_type columns to content_type and content_structure
-- Date: 2025-11-26

BEGIN;

-- 1. ContentIdeas table (igny8_content_ideas)
ALTER TABLE igny8_content_ideas RENAME COLUMN site_entity_type TO content_type;
ALTER TABLE igny8_content_ideas RENAME COLUMN cluster_role TO content_structure;

-- Update index names for ContentIdeas
DROP INDEX IF EXISTS igny8_content_ideas_site_entity_type_idx;
DROP INDEX IF EXISTS igny8_content_ideas_cluster_role_idx;
CREATE INDEX igny8_content_ideas_content_type_idx ON igny8_content_ideas(content_type);
CREATE INDEX igny8_content_ideas_content_structure_idx ON igny8_content_ideas(content_structure);

-- 2. Tasks table (igny8_tasks)
ALTER TABLE igny8_tasks RENAME COLUMN entity_type TO content_type;
-- cluster_role already mapped via db_column, but let's check if column exists
DO $$
BEGIN
    IF EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'igny8_tasks' AND column_name = 'cluster_role') THEN
        ALTER TABLE igny8_tasks RENAME COLUMN cluster_role TO content_structure;
    END IF;
END $$;

-- 3. Content table (igny8_content)
ALTER TABLE igny8_content RENAME COLUMN entity_type TO content_type;
-- cluster_role already mapped via db_column, but let's check if column exists
DO $$
BEGIN
    IF EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'igny8_content' AND column_name = 'cluster_role') THEN
        ALTER TABLE igny8_content RENAME COLUMN cluster_role TO content_structure;
    END IF;
END $$;

-- 4. ContentTaxonomy table (igny8_content_taxonomy)
DO $$
BEGIN
    IF EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'igny8_content_taxonomy' AND column_name = 'entity_type') THEN
        ALTER TABLE igny8_content_taxonomy RENAME COLUMN entity_type TO content_type;
    END IF;
END $$;

-- 5. AITaskExecution table (igny8_ai_task_execution)
DO $$
BEGIN
    IF EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'igny8_ai_task_execution' AND column_name = 'entity_type') THEN
        ALTER TABLE igny8_ai_task_execution RENAME COLUMN entity_type TO content_type;
    END IF;
END $$;

COMMIT;
