-- Rollback: Restore status_id foreign key from in_progress boolean

-- Step 1: Recreate the task_taskstatus table
CREATE TABLE IF NOT EXISTS task_taskstatus (
    id SERIAL PRIMARY KEY,
    created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
    deleted_at TIMESTAMPTZ,
    name VARCHAR(20) NOT NULL,
    description TEXT,
    color VARCHAR(7),
    display_order INTEGER NOT NULL DEFAULT 0
);

-- Step 2: Seed the status lookup data
INSERT INTO task_taskstatus (name, description, color, display_order) VALUES
    ('Pending', 'Task is waiting to be started', '#808080', 1),
    ('In Progress', 'Task is currently being worked on', '#3498db', 2),
    ('Completed', 'Task has been finished', '#27ae60', 3),
    ('On Hold', 'Task is temporarily paused', '#f39c12', 4),
    ('Cancelled', 'Task has been cancelled', '#e74c3c', 5)
ON CONFLICT DO NOTHING;

-- Step 3: Add status_id column back
ALTER TABLE task_task ADD COLUMN IF NOT EXISTS status_id INTEGER;

-- Step 4: Migrate data - set status_id based on in_progress flag
-- Set to "In Progress" status if in_progress is true, otherwise "Pending"
UPDATE task_task
SET status_id = (
    CASE
        WHEN in_progress = true THEN (SELECT id FROM task_taskstatus WHERE name = 'In Progress' LIMIT 1)
        ELSE (SELECT id FROM task_taskstatus WHERE name = 'Pending' LIMIT 1)
    END
);

-- Step 5: Add foreign key constraint
ALTER TABLE task_task ADD CONSTRAINT fk_task_task_status
    FOREIGN KEY (status_id) REFERENCES task_taskstatus(id);

-- Step 6: Drop the in_progress column
ALTER TABLE task_task DROP COLUMN IF EXISTS in_progress;

-- Step 7: Drop the index
DROP INDEX IF EXISTS idx_task_task_in_progress;
