-- Migration: Move existing kanban boards to documents table
-- This creates document entries for each kanban_board with type 'kanban'
-- The content field stores reference to the board_id for backwards compatibility

-- Insert existing kanban boards as documents
INSERT INTO documents (id, org_id, parent_id, type, name, path, position, content, created_by, created_at, updated_at)
SELECT 
    kb.id,
    kb.org_id,
    NULL as parent_id,
    'kanban' as type,
    kb.name,
    '/' || kb.name as path,
    COALESCE((
        SELECT COUNT(*) FROM documents d 
        WHERE d.org_id = kb.org_id AND d.parent_id IS NULL
    ), 0) as position,
    jsonb_build_object(
        'type', 'kanban',
        'board_id', kb.id
    ) as content,
    COALESCE(kb.created_by, (
        SELECT user_id FROM org_members 
        WHERE org_id = kb.org_id 
        ORDER BY invited_at ASC 
        LIMIT 1
    )) as created_by,
    kb.created_at,
    kb.created_at as updated_at
FROM kanban_boards kb
WHERE NOT EXISTS (
    SELECT 1 FROM documents d 
    WHERE d.id = kb.id
);

-- Update any duplicate paths by appending board ID
UPDATE documents 
SET path = path || '-' || SUBSTRING(id::text, 1, 8)
WHERE type = 'kanban' 
AND id IN (
    SELECT d1.id 
    FROM documents d1 
    JOIN documents d2 ON d1.path = d2.path AND d1.id != d2.id
    WHERE d1.type = 'kanban'
);
