-- Multi-Branch Approval System Database Migration Script
-- Run this script to add multi-branch support to existing database

-- =====================================================
-- 1. ADD NEW COLUMNS TO APPROVAL_WORKFLOW_STEPS TABLE
-- =====================================================

-- Add multi-branch support fields
ALTER TABLE approval_workflow_steps 
ADD COLUMN IF NOT EXISTS parent_step_id INT REFERENCES approval_workflow_steps(id);

ALTER TABLE approval_workflow_steps 
ADD COLUMN IF NOT EXISTS condition_type VARCHAR(50);

ALTER TABLE approval_workflow_steps 
ADD COLUMN IF NOT EXISTS condition_value TEXT;

ALTER TABLE approval_workflow_steps 
ADD COLUMN IF NOT EXISTS is_parallel BOOLEAN DEFAULT false;

ALTER TABLE approval_workflow_steps 
ADD COLUMN IF NOT EXISTS branch_name VARCHAR(100);

ALTER TABLE approval_workflow_steps 
ADD COLUMN IF NOT EXISTS branch_order INT;

-- =====================================================
-- 2. ADD NEW COLUMNS TO ARTICLE_APPROVAL_FLOWS TABLE
-- =====================================================

-- Add multi-branch support fields
ALTER TABLE article_approval_flows 
ADD COLUMN IF NOT EXISTS current_branch VARCHAR(100);

ALTER TABLE article_approval_flows 
ADD COLUMN IF NOT EXISTS branch_path TEXT;

ALTER TABLE article_approval_flows 
ADD COLUMN IF NOT EXISTS is_parallel_flow BOOLEAN DEFAULT false;

ALTER TABLE article_approval_flows 
ADD COLUMN IF NOT EXISTS parent_flow_id INT REFERENCES article_approval_flows(id);

-- =====================================================
-- 3. CREATE INDEXES FOR PERFORMANCE
-- =====================================================

-- Indexes for approval_workflow_steps
CREATE INDEX IF NOT EXISTS idx_approval_workflow_steps_condition 
ON approval_workflow_steps(condition_type, branch_name);

CREATE INDEX IF NOT EXISTS idx_approval_workflow_steps_parent 
ON approval_workflow_steps(parent_step_id);

CREATE INDEX IF NOT EXISTS idx_approval_workflow_steps_branch 
ON approval_workflow_steps(branch_name, branch_order);

-- Indexes for article_approval_flows
CREATE INDEX IF NOT EXISTS idx_article_approval_flows_branch 
ON article_approval_flows(current_branch);

CREATE INDEX IF NOT EXISTS idx_article_approval_flows_parent 
ON article_approval_flows(parent_flow_id);

CREATE INDEX IF NOT EXISTS idx_article_approval_flows_parallel 
ON article_approval_flows(is_parallel_flow);

-- =====================================================
-- 4. MIGRATE EXISTING DATA
-- =====================================================

-- Set default values for existing approval_workflow_steps
UPDATE approval_workflow_steps 
SET 
  condition_type = 'always',
  branch_name = 'default_branch',
  branch_order = step_order,
  is_parallel = false
WHERE condition_type IS NULL;

-- Set default values for existing article_approval_flows
UPDATE article_approval_flows 
SET 
  current_branch = 'default_branch',
  branch_path = '["default_branch"]',
  is_parallel_flow = false
WHERE current_branch IS NULL;

-- =====================================================
-- 5. CREATE DEFAULT MULTI-BRANCH WORKFLOW
-- =====================================================

-- Insert default multi-branch workflow
INSERT INTO approval_workflows (name, description, is_active, is_default, requires_approval, auto_publish, created_at, updated_at)
VALUES (
  'Default Multi-Branch Approval',
  'Default workflow dengan multi-branch support',
  true,
  true,
  true,
  false,
  NOW(),
  NOW()
);

-- Get the workflow ID (assuming it's the last inserted)
-- Note: In production, you might want to use a specific ID or handle this differently
DO $$
DECLARE
    workflow_id_var INT;
BEGIN
    -- Get the ID of the workflow we just created
    SELECT id INTO workflow_id_var 
    FROM approval_workflows 
    WHERE name = 'Default Multi-Branch Approval' 
    ORDER BY id DESC 
    LIMIT 1;

    -- Insert workflow steps for the multi-branch workflow
    INSERT INTO approval_workflow_steps (
        workflow_id, step_order, step_name, required_user_level_id, 
        can_skip, is_active, condition_type, condition_value, 
        branch_name, branch_order, created_at, updated_at
    ) VALUES 
    -- Step 1: Branch A (Level 2) - for user levels 4,5,6
    (
        workflow_id_var, 1, 'Level 2 Branch', 2, 
        false, true, 'user_level_hierarchy', 
        '{"applies_to_levels": [4,5,6]}', 
        'Branch_A', 1, NOW(), NOW()
    ),
    -- Step 1: Branch B (Level 3) - for user levels 7,8,9
    (
        workflow_id_var, 1, 'Level 3 Branch', 3, 
        false, true, 'user_level_hierarchy', 
        '{"applies_to_levels": [7,8,9]}', 
        'Branch_B', 1, NOW(), NOW()
    ),
    -- Step 1: Branch C (Level 3) - for user levels 10,11,12
    (
        workflow_id_var, 1, 'Level 3 Branch C', 3, 
        false, true, 'user_level_hierarchy', 
        '{"applies_to_levels": [10,11,12]}', 
        'Branch_C', 1, NOW(), NOW()
    ),
    -- Step 2: Final Approval (Level 1) - always applies
    (
        workflow_id_var, 2, 'Level 1 Final Approval', 1, 
        false, true, 'always', 
        '{}', 
        'Final_Approval', 1, NOW(), NOW()
    );
END $$;

-- =====================================================
-- 6. UPDATE EXISTING ARTICLES TO USE NEW WORKFLOW
-- =====================================================

-- Update existing articles to use the new default workflow
UPDATE articles 
SET workflow_id = (
    SELECT id FROM approval_workflows 
    WHERE name = 'Default Multi-Branch Approval' 
    ORDER BY id DESC 
    LIMIT 1
)
WHERE workflow_id IS NULL;

-- =====================================================
-- 7. CREATE SAMPLE DATA FOR TESTING
-- =====================================================

-- Insert sample user levels if they don't exist
INSERT INTO user_levels (name, alias_name, level_number, is_active, created_at, updated_at)
VALUES 
    ('Level 1', 'L1', 1, true, NOW(), NOW()),
    ('Level 2', 'L2', 2, true, NOW(), NOW()),
    ('Level 3', 'L3', 3, true, NOW(), NOW()),
    ('Level 4', 'L4', 4, true, NOW(), NOW()),
    ('Level 5', 'L5', 5, true, NOW(), NOW()),
    ('Level 6', 'L6', 6, true, NOW(), NOW()),
    ('Level 7', 'L7', 7, true, NOW(), NOW()),
    ('Level 8', 'L8', 8, true, NOW(), NOW()),
    ('Level 9', 'L9', 9, true, NOW(), NOW()),
    ('Level 10', 'L10', 10, true, NOW(), NOW()),
    ('Level 11', 'L11', 11, true, NOW(), NOW()),
    ('Level 12', 'L12', 12, true, NOW(), NOW())
ON CONFLICT (level_number) DO NOTHING;

-- =====================================================
-- 8. VERIFICATION QUERIES
-- =====================================================

-- Verify the migration was successful
SELECT 'Migration completed successfully' as status;

-- Check workflow steps
SELECT 
    aws.id,
    aws.step_order,
    aws.step_name,
    aws.required_user_level_id,
    aws.condition_type,
    aws.condition_value,
    aws.branch_name,
    aws.branch_order,
    aw.name as workflow_name
FROM approval_workflow_steps aws
JOIN approval_workflows aw ON aws.workflow_id = aw.id
WHERE aw.name = 'Default Multi-Branch Approval'
ORDER BY aws.step_order, aws.branch_order;

-- Check user levels
SELECT id, name, level_number, is_active 
FROM user_levels 
ORDER BY level_number;

-- Check articles with workflow assignments
SELECT 
    a.id,
    a.title,
    a.workflow_id,
    aw.name as workflow_name
FROM articles a
LEFT JOIN approval_workflows aw ON a.workflow_id = aw.id
LIMIT 10;

-- =====================================================
-- 9. ROLLBACK SCRIPT (if needed)
-- =====================================================

/*
-- Uncomment and run this section if you need to rollback the migration

-- Drop indexes
DROP INDEX IF EXISTS idx_approval_workflow_steps_condition;
DROP INDEX IF EXISTS idx_approval_workflow_steps_parent;
DROP INDEX IF EXISTS idx_approval_workflow_steps_branch;
DROP INDEX IF EXISTS idx_article_approval_flows_branch;
DROP INDEX IF EXISTS idx_article_approval_flows_parent;
DROP INDEX IF EXISTS idx_article_approval_flows_parallel;

-- Drop new columns from approval_workflow_steps
ALTER TABLE approval_workflow_steps DROP COLUMN IF EXISTS parent_step_id;
ALTER TABLE approval_workflow_steps DROP COLUMN IF EXISTS condition_type;
ALTER TABLE approval_workflow_steps DROP COLUMN IF EXISTS condition_value;
ALTER TABLE approval_workflow_steps DROP COLUMN IF EXISTS is_parallel;
ALTER TABLE approval_workflow_steps DROP COLUMN IF EXISTS branch_name;
ALTER TABLE approval_workflow_steps DROP COLUMN IF EXISTS branch_order;

-- Drop new columns from article_approval_flows
ALTER TABLE article_approval_flows DROP COLUMN IF EXISTS current_branch;
ALTER TABLE article_approval_flows DROP COLUMN IF EXISTS branch_path;
ALTER TABLE article_approval_flows DROP COLUMN IF EXISTS is_parallel_flow;
ALTER TABLE article_approval_flows DROP COLUMN IF EXISTS parent_flow_id;

-- Remove default multi-branch workflow
DELETE FROM approval_workflow_steps 
WHERE workflow_id IN (
    SELECT id FROM approval_workflows 
    WHERE name = 'Default Multi-Branch Approval'
);

DELETE FROM approval_workflows 
WHERE name = 'Default Multi-Branch Approval';

SELECT 'Rollback completed successfully' as status;
*/

-- =====================================================
-- 10. PERFORMANCE OPTIMIZATION
-- =====================================================

-- Update table statistics
ANALYZE approval_workflow_steps;
ANALYZE article_approval_flows;
ANALYZE approval_workflows;
ANALYZE user_levels;

-- =====================================================
-- END OF MIGRATION SCRIPT
-- =====================================================
