-- Migration: Add task drafts tables
-- Date: 2026-01-26
--
-- This migration creates tables for storing task drafts:
-- 1. task_drafts - main table for task drafts with progression value and auto_complete flag
-- 2. task_draft_subtasks - stores only checked subtask IDs for each draft

-- ============================================
-- Table: task_drafts
-- ============================================
CREATE TABLE task_drafts (
    id SERIAL PRIMARY KEY,
    task_id INTEGER REFERENCES tasks(id) ON DELETE CASCADE,
    user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
    progression_value NUMERIC(10,4),
    auto_complete BOOLEAN DEFAULT FALSE,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    UNIQUE(task_id)
);

CREATE INDEX idx_task_drafts_task_id ON task_drafts(task_id);
CREATE INDEX idx_task_drafts_user_id ON task_drafts(user_id);
CREATE INDEX idx_task_drafts_auto_complete ON task_drafts(auto_complete) WHERE auto_complete = TRUE;

COMMENT ON TABLE task_drafts IS 'Stores draft states for tasks with progression value and auto-complete flag';
COMMENT ON COLUMN task_drafts.progression_value IS 'Saved progression value from user input';
COMMENT ON COLUMN task_drafts.auto_complete IS 'Flag indicating task should be auto-completed at end of day (23:55)';
COMMENT ON COLUMN task_drafts.task_id IS 'Reference to task. UNIQUE constraint ensures one draft per task';

-- ============================================
-- Table: task_draft_subtasks
-- ============================================
CREATE TABLE task_draft_subtasks (
    id SERIAL PRIMARY KEY,
    task_draft_id INTEGER REFERENCES task_drafts(id) ON DELETE CASCADE,
    subtask_id INTEGER REFERENCES tasks(id) ON DELETE CASCADE,
    UNIQUE(task_draft_id, subtask_id)
);

CREATE INDEX idx_task_draft_subtasks_task_draft_id ON task_draft_subtasks(task_draft_id);
CREATE INDEX idx_task_draft_subtasks_subtask_id ON task_draft_subtasks(subtask_id);

COMMENT ON TABLE task_draft_subtasks IS 'Stores only checked subtask IDs for each draft. If subtask is not in this table, it means it is unchecked';
COMMENT ON COLUMN task_draft_subtasks.subtask_id IS 'Reference to subtask task. Only checked subtasks are stored here';
