-- Migration 005: Add assignees, milestone, and due_date support
-- Schema version: 5

-- Add new columns to issues table
ALTER TABLE issues ADD COLUMN due_date TEXT;           -- YYYY-MM-DD format, nullable
ALTER TABLE issues ADD COLUMN milestone_id INTEGER;    -- Local milestone ID (FK to milestones.id)
ALTER TABLE issues ADD COLUMN milestone_title TEXT;    -- Denormalized for quick display

-- Milestones table (captures key fields for filtering and display)
CREATE TABLE IF NOT EXISTS milestones (
    id INTEGER PRIMARY KEY,
    gitlab_id INTEGER NOT NULL,
    project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
    iid INTEGER NOT NULL,                              -- Project-scoped milestone number
    title TEXT NOT NULL,
    description TEXT,
    state TEXT,                                        -- 'active' or 'closed'
    due_date TEXT,                                     -- YYYY-MM-DD
    web_url TEXT,
    UNIQUE(project_id, gitlab_id)
);

CREATE INDEX IF NOT EXISTS idx_milestones_project ON milestones(project_id);
CREATE INDEX IF NOT EXISTS idx_milestones_state ON milestones(project_id, state);

-- Issue assignees junction table (issues can have multiple assignees)
CREATE TABLE IF NOT EXISTS issue_assignees (
    issue_id INTEGER NOT NULL REFERENCES issues(id) ON DELETE CASCADE,
    username TEXT NOT NULL,
    PRIMARY KEY (issue_id, username)
);

CREATE INDEX IF NOT EXISTS idx_issue_assignees_username ON issue_assignees(username);

-- Index for due_date filtering
CREATE INDEX IF NOT EXISTS idx_issues_due_date ON issues(due_date);

-- Index for milestone filtering
CREATE INDEX IF NOT EXISTS idx_issues_milestone ON issues(milestone_id);

-- Update schema version
INSERT INTO schema_version (version, applied_at, description)
VALUES (5, strftime('%s', 'now') * 1000, 'Add assignees, milestone, and due_date support');
