import type { RequestHandler } from './$types';
import { getDb } from '$lib/server/db';
import { fetchAllowedUserGroups } from '$lib/server/task-helpers';

export const GET: RequestHandler = async (event) => {
	// Requiere sesión
	const userId = event.locals.userId ?? null;
	if (!userId) {
		return new Response('Unauthorized', { status: 401 });
	}

	const db = await getDb();

	// Listar solo grupos permitidos donde el usuario está activo
	const groups = fetchAllowedUserGroups(db, userId);

	// Preparar statements para contadores
	const countOpenStmt = db.prepare(
		`SELECT COUNT(*) AS cnt
     FROM tasks t
     WHERE t.group_id = ?
       AND COALESCE(t.completed, 0) = 0
       AND t.completed_at IS NULL`
	);
	const countUnassignedStmt = db.prepare(
		`SELECT COUNT(*) AS cnt
     FROM tasks t
     WHERE t.group_id = ?
       AND COALESCE(t.completed, 0) = 0
       AND t.completed_at IS NULL
       AND NOT EXISTS (SELECT 1 FROM task_assignments a WHERE a.task_id = t.id)`
	);

	const items = groups.map((g) => {
		const open = countOpenStmt.get(g.id) as any;
		const unassigned = countUnassignedStmt.get(g.id) as any;
		return {
			id: String(g.id),
			name: g.name != null ? String(g.name) : null,
			counts: {
				open: Number(open?.cnt || 0),
				unassigned: Number(unassigned?.cnt || 0)
			}
		};
	});

	return new Response(JSON.stringify({ items }), {
		status: 200,
		headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }
	});
};
