import crypto from 'node:crypto';
export async function kanbanRoutes(app, opts) {
    const { db } = opts;
    // GET /api/kanban/tasks — all squads (MUST be before /:squad routes)
    app.get('/api/kanban/tasks', {
        preHandler: [app.requireAuth],
    }, async (request, reply) => {
        const { status, limit: limitStr, offset: offsetStr } = request.query;
        const limit = Math.min(Math.max(parseInt(limitStr || '200', 10) || 200, 1), 500);
        const offset = Math.max(parseInt(offsetStr || '0', 10) || 0, 0);
        let query = 'SELECT * FROM kanban_tasks';
        const params = [];
        if (status) {
            const statuses = status.split(',').filter(s => ['planned', 'executing', 'done', 'failed'].includes(s));
            if (statuses.length > 0) {
                query += ` WHERE status IN (${statuses.map(() => '?').join(',')})`;
                params.push(...statuses);
            }
        }
        query += ' ORDER BY created_at DESC LIMIT ? OFFSET ?';
        params.push(limit, offset);
        const rows = db.prepare(query).all(...params);
        return reply.send(rows);
    });
    // GET /api/kanban/:squad/tasks
    app.get('/api/kanban/:squad/tasks', {
        preHandler: [app.requireAuth],
    }, async (request, reply) => {
        const { squad } = request.params;
        const rows = db.prepare('SELECT * FROM kanban_tasks WHERE squad_code = ? ORDER BY status, position, created_at').all(squad);
        return reply.send(rows);
    });
    // GET /api/kanban/:squad/tasks/:id — single task with full details
    app.get('/api/kanban/:squad/tasks/:id', {
        preHandler: [app.requireAuth],
    }, async (request, reply) => {
        const { squad, id } = request.params;
        const task = db.prepare('SELECT * FROM kanban_tasks WHERE id = ? AND squad_code = ?').get(id, squad);
        if (!task) {
            return reply.code(404).send({ error: 'Task not found' });
        }
        return reply.send(task);
    });
    // POST /api/kanban/:squad/tasks
    app.post('/api/kanban/:squad/tasks', {
        preHandler: [app.requireAuth],
    }, async (request, reply) => {
        const { squad } = request.params;
        const { title, description, status } = request.body;
        if (!title || typeof title !== 'string' || !title.trim()) {
            return reply.code(400).send({ error: 'title is required' });
        }
        const taskStatus = status || 'planned';
        if (!['planned', 'executing', 'done', 'failed'].includes(taskStatus)) {
            return reply.code(400).send({ error: 'Invalid status' });
        }
        // Get next position for this status
        const maxPos = db.prepare('SELECT COALESCE(MAX(position), -1) as maxPos FROM kanban_tasks WHERE squad_code = ? AND status = ?').get(squad, taskStatus);
        const id = crypto.randomUUID();
        const now = new Date().toISOString();
        const startedAt = taskStatus === 'executing' ? now : null;
        const finishedAt = taskStatus === 'done' ? now : null;
        db.prepare(`INSERT INTO kanban_tasks (id, squad_code, title, description, status, position, result, started_at, finished_at, created_at, updated_at)
       VALUES (?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?)`).run(id, squad, title.trim(), description?.trim() || null, taskStatus, maxPos.maxPos + 1, startedAt, finishedAt, now, now);
        const task = db.prepare('SELECT * FROM kanban_tasks WHERE id = ?').get(id);
        return reply.code(201).send(task);
    });
    // PATCH /api/kanban/:squad/tasks/:id
    app.patch('/api/kanban/:squad/tasks/:id', {
        preHandler: [app.requireAuth],
    }, async (request, reply) => {
        const { squad, id } = request.params;
        const { title, description, status, position, result } = request.body;
        const existing = db.prepare('SELECT * FROM kanban_tasks WHERE id = ? AND squad_code = ?').get(id, squad);
        if (!existing) {
            return reply.code(404).send({ error: 'Task not found' });
        }
        if (status && !['planned', 'executing', 'done', 'failed'].includes(status)) {
            return reply.code(400).send({ error: 'Invalid status' });
        }
        const newTitle = title?.trim() || existing.title;
        const newDescription = description !== undefined ? (description?.trim() || null) : existing.description;
        const newStatus = status || existing.status;
        const newResult = result !== undefined ? result : existing.result;
        let newPosition = position ?? existing.position;
        // Auto-set timestamps on status transitions
        let startedAt = existing.started_at;
        let finishedAt = existing.finished_at;
        if (status && status !== existing.status) {
            if (status === 'executing' && !existing.started_at) {
                startedAt = new Date().toISOString();
            }
            if (status === 'done') {
                finishedAt = new Date().toISOString();
            }
            if (status === 'failed') {
                finishedAt = new Date().toISOString();
            }
            // If moved back to planned, clear timestamps
            if (status === 'planned') {
                startedAt = null;
                finishedAt = null;
            }
        }
        // If status changed, put at end of new column
        if (status && status !== existing.status && position === undefined) {
            const maxPos = db.prepare('SELECT COALESCE(MAX(position), -1) as maxPos FROM kanban_tasks WHERE squad_code = ? AND status = ?').get(squad, newStatus);
            newPosition = maxPos.maxPos + 1;
        }
        const now = new Date().toISOString();
        db.prepare(`UPDATE kanban_tasks SET title = ?, description = ?, status = ?, position = ?, result = ?, started_at = ?, finished_at = ?, updated_at = ? WHERE id = ?`).run(newTitle, newDescription, newStatus, newPosition, newResult, startedAt, finishedAt, now, id);
        const updated = db.prepare('SELECT * FROM kanban_tasks WHERE id = ?').get(id);
        return reply.send(updated);
    });
    // DELETE /api/kanban/:squad/tasks/:id
    app.delete('/api/kanban/:squad/tasks/:id', {
        preHandler: [app.requireAuth],
    }, async (request, reply) => {
        const { squad, id } = request.params;
        const existing = db.prepare('SELECT id FROM kanban_tasks WHERE id = ? AND squad_code = ?').get(id, squad);
        if (!existing) {
            return reply.code(404).send({ error: 'Task not found' });
        }
        db.prepare('DELETE FROM kanban_tasks WHERE id = ?').run(id);
        return reply.code(204).send();
    });
}
//# sourceMappingURL=kanban-routes.js.map