/**
 * Kanban board view — returns jobs grouped by status lane.
 * Reads from vw_kanban SQL view; no business logic here.
 */
const ALL_LANES = ['backlog', 'ready', 'claimed', 'wip', 'blocked', 'review', 'done', 'failed', 'cancelled'];
function parsePayload(raw) {
    if (!raw)
        return {};
    try {
        const parsed = JSON.parse(raw);
        return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
    }
    catch {
        return {};
    }
}
export function getKanbanBoard(db, client) {
    const rows = client
        ? db.prepare(`SELECT * FROM vw_kanban WHERE client = ?`).all(client)
        : db.prepare(`SELECT * FROM vw_kanban`).all();
    const lanes = {};
    for (const l of ALL_LANES)
        lanes[l] = [];
    for (const r of rows) {
        lanes[r.lane]?.push({
            id: r.id,
            title: r.title,
            workerId: r.worker_id,
            priority: r.priority,
            tokensUsed: r.tokens_used,
            budgetCapUsd: r.budget_cap_usd,
            payload: parsePayload(r.payload),
            client: r.client,
            createdAt: r.created_at,
            claimedAt: r.claimed_at,
            completedAt: r.completed_at,
        });
    }
    return {
        lanes,
        totalJobs: rows.length,
        generatedAt: Date.now(),
    };
}
export function getLaneJobs(db, lane) {
    const rows = db.prepare(`SELECT * FROM vw_kanban WHERE lane = ? ORDER BY priority, created_at`).all(lane);
    return rows.map((r) => ({
        id: r.id,
        title: r.title,
        workerId: r.worker_id,
        priority: r.priority,
        tokensUsed: r.tokens_used,
        budgetCapUsd: r.budget_cap_usd,
        payload: parsePayload(r.payload),
        client: r.client,
        createdAt: r.created_at,
        claimedAt: r.claimed_at,
        completedAt: r.completed_at,
    }));
}
