-- Migration: Replace status_id foreign key with in_progress boolean
-- This simplifies the task model since status was only used to determine if a task is "In Progress"

-- Step 1: Add in_progress boolean column with default false
ALTER TABLE task_task ADD COLUMN IF NOT EXISTS in_progress BOOLEAN NOT NULL DEFAULT false;

-- Step 2: Create index on in_progress for query performance
CREATE INDEX IF NOT EXISTS idx_task_task_in_progress ON task_task(in_progress);

-- Step 3: Migrate existing data - set in_progress = true for tasks with "In Progress" status
UPDATE task_task
SET in_progress = true
WHERE status_id IN (
    SELECT id FROM task_taskstatus WHERE LOWER(name) = 'in progress'
);

-- Step 4: Drop the foreign key constraint on status_id (if it exists)
-- PostgreSQL syntax - the constraint name might vary
DO $$
BEGIN
    -- Try to drop the constraint if it exists
    IF EXISTS (
        SELECT 1 FROM information_schema.table_constraints
        WHERE constraint_name = 'fk_task_task_status'
        AND table_name = 'task_task'
    ) THEN
        ALTER TABLE task_task DROP CONSTRAINT fk_task_task_status;
    END IF;

    -- Also try the gorm auto-generated constraint name
    IF EXISTS (
        SELECT 1 FROM information_schema.table_constraints
        WHERE constraint_name = 'task_task_status_id_fkey'
        AND table_name = 'task_task'
    ) THEN
        ALTER TABLE task_task DROP CONSTRAINT task_task_status_id_fkey;
    END IF;
END $$;

-- Step 5: Drop the status_id column
ALTER TABLE task_task DROP COLUMN IF EXISTS status_id;

-- Step 6: Drop the task_taskstatus table
DROP TABLE IF EXISTS task_taskstatus;
