-- Project-specific card statuses. Every project gets a "To do" / "Doing" /
-- "Done" set when it is created (see CardStatusRepository::seedDefaults); the
-- backfill below covers projects that already existed.
CREATE TABLE IF NOT EXISTS card_statuses (
    id         INTEGER PRIMARY KEY AUTOINCREMENT,
    project_id INTEGER NOT NULL REFERENCES projects (id) ON DELETE CASCADE,
    name       TEXT NOT NULL,
    position   INTEGER NOT NULL DEFAULT 0,
    created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
    updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now'))
);

CREATE INDEX IF NOT EXISTS idx_card_statuses_project_position
    ON card_statuses (project_id, position);

-- Nullable, and left NULL for existing cards: a card without a status sits in
-- the project "inbox" until the user gives it one. Losing a status (a deleted
-- status row) clears the link rather than removing the card.
ALTER TABLE cards
    ADD COLUMN status_id INTEGER REFERENCES card_statuses (id) ON DELETE SET NULL;

CREATE INDEX IF NOT EXISTS idx_cards_status ON cards (status_id);

-- Backfill: give every pre-existing project the default status set.
INSERT INTO card_statuses (project_id, name, position)
SELECT p.id, d.name, d.position
FROM projects p
CROSS JOIN (
             SELECT 'To do' AS name, 0 AS position
    UNION ALL SELECT 'Doing',        1
    UNION ALL SELECT 'Done',         2
) d;
