-- Kanban: brett, kolonner og kort
-- Kort er nodes i kunnskapsgrafen (kan kobles til temaer/aktører senere).
-- Kolonner er IKKE nodes — de er intern struktur for brettet.
-- Posisjon bruker REAL for midtpunkts-innsetting uten re-nummerering.

BEGIN;

-- ============================================================
-- Kanban boards (er nodes → arver workspace via nodes-tabellen)
-- ============================================================

CREATE TABLE kanban_boards (
    id        UUID PRIMARY KEY REFERENCES nodes(id) ON DELETE CASCADE,
    parent_id UUID NOT NULL REFERENCES nodes(id) ON DELETE CASCADE,
    name      TEXT NOT NULL DEFAULT 'Kanban'
);

CREATE INDEX idx_kanban_boards_parent ON kanban_boards(parent_id);

-- ============================================================
-- Kolonner
-- ============================================================

CREATE TABLE kanban_columns (
    id        UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    board_id  UUID NOT NULL REFERENCES kanban_boards(id) ON DELETE CASCADE,
    name      TEXT NOT NULL,
    color     TEXT,           -- valgfri hex-fargekode (#ff6b6b)
    position  REAL NOT NULL DEFAULT 0,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX idx_kanban_columns_board ON kanban_columns(board_id, position);

-- ============================================================
-- Kort (er nodes → kan kobles i grafen, arver workspace)
-- ============================================================

CREATE TABLE kanban_cards (
    id          UUID PRIMARY KEY REFERENCES nodes(id) ON DELETE CASCADE,
    column_id   UUID NOT NULL REFERENCES kanban_columns(id) ON DELETE CASCADE,
    title       TEXT NOT NULL,
    description TEXT,
    assignee_id TEXT REFERENCES users(authentik_id) ON DELETE SET NULL,
    position    REAL NOT NULL DEFAULT 0,
    created_by  TEXT REFERENCES users(authentik_id) ON DELETE SET NULL,
    created_at  TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at  TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX idx_kanban_cards_column ON kanban_cards(column_id, position);

CREATE TRIGGER trg_kanban_cards_updated_at BEFORE UPDATE ON kanban_cards
    FOR EACH ROW EXECUTE FUNCTION set_updated_at();

-- ============================================================
-- Utvid node_type enum med 'kanban_board' og 'kanban_card'
-- ============================================================

ALTER TYPE node_type ADD VALUE IF NOT EXISTS 'kanban_board';
ALTER TYPE node_type ADD VALUE IF NOT EXISTS 'kanban_card';

COMMIT;
