import type { RequestHandler } from './$types';
import { getDb } from '$lib/server/db';
import { loadAssignees, checkGroupAccess, mapTaskRow } 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 groupId = event.params.id;
	if (!groupId) {
		return new Response('Bad Request', { status: 400 });
	}

	const url = new URL(event.request.url);
	const unassignedFirst =
		(url.searchParams.get('unassignedFirst') || '').trim().toLowerCase() === 'true';
	const onlyUnassigned =
		(url.searchParams.get('onlyUnassigned') || '').trim().toLowerCase() === 'true';
	let limit = parseInt(url.searchParams.get('limit') || '', 10);
	if (!Number.isFinite(limit) || limit <= 0) limit = 0;
	if (limit > 100) limit = 100;

	const db = await getDb();

	// Gating: grupo permitido + usuario es miembro activo
	const accessCheck = checkGroupAccess(db, groupId, userId);
	if (accessCheck instanceof Response) return accessCheck;

	const orderParts: string[] = [];
	if (unassignedFirst) {
		orderParts.push(
			`CASE WHEN EXISTS (SELECT 1 FROM task_assignments a WHERE a.task_id = t.id) THEN 1 ELSE 0 END ASC`
		);
	}
	orderParts.push(
		`CASE WHEN t.due_date IS NULL THEN 1 ELSE 0 END`,
		`t.due_date ASC`,
		`t.id ASC`
	);

	const whereParts = [
		`t.group_id = ?`,
		`COALESCE(t.completed, 0) = 0`,
		`t.completed_at IS NULL`
	];
	if (onlyUnassigned) {
		whereParts.push(
			`NOT EXISTS (SELECT 1 FROM task_assignments a WHERE a.task_id = t.id)`
		);
	}

	const params: any[] = [groupId];

	const sql = `
			SELECT t.id, t.description, t.due_date, t.group_id, t.display_code
       FROM tasks t
       WHERE ${whereParts.join(' AND ')}
       ORDER BY ${orderParts.join(', ')}${limit > 0 ? ' LIMIT ?' : ''}`;

	if (limit > 0) params.push(limit);

	const rows = db.prepare(sql).all(...params) as any[];

	let items = rows.map(mapTaskRow);

	// Cargar asignados (skip when onlyUnassigned)
	if (!onlyUnassigned) {
		loadAssignees(db, items, null);
	}

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