import type { PageServerLoad } from './$types';
import { redirect } from '@sveltejs/kit';

export const load: PageServerLoad = async (event) => {
	const userId = event.locals.userId ?? null;
	if (!userId) {
		// No hay sesión: redirigir a la home
		throw redirect(303, '/');
	}

	// Parámetros de orden y paginación
	const orderParam = (event.url.searchParams.get('order') || 'due').trim().toLowerCase();
	const order: 'due' | 'group' = orderParam === 'group' ? 'group' : 'due';
	const pageStr = (event.url.searchParams.get('page') || '1').trim();
	const page = Math.max(1, parseInt(pageStr, 10) || 1);

	// Cargar "mis tareas" desde la API interna
	let openTasks: Array<{
		id: number;
		description: string;
		due_date: string | null;
		group_id: string | null;
		display_code: number | null;
		assignees: string[];
	}> = [];
	let recentTasks: Array<{
		id: number;
		description: string;
		due_date: string | null;
		group_id: string | null;
		display_code: number | null;
		assignees: string[];
		completed?: boolean;
		completed_at?: string | null;
	}> = [];
	let hasMore: boolean = false;

	// Agregado: "Sin responsable de mis grupos"
	let unassignedOpen: Array<{
		id: number;
		description: string;
		due_date: string | null;
		group_id: string | null;
		display_code: number | null;
		assignees: string[];
	}> = [];
	const groupNames: Record<string, string> = {};

	try {
		// Mis tareas abiertas (paginadas, orden controlado por el servidor)
		const orderParamApi = order === 'group' ? 'group_then_due' : 'due';
		let fetchUrl = `/api/me/tasks?limit=20&order=${encodeURIComponent(orderParamApi)}`;
		fetchUrl += `&page=${encodeURIComponent(String(page))}`;

		const res = await event.fetch(fetchUrl, { headers: { 'cache-control': 'no-store' } });
		if (res.ok) {
			const json = await res.json();
			openTasks = Array.isArray(json?.items) ? json.items : [];
			hasMore = Boolean(json?.hasMore);
		}

		// Completadas en las últimas 24h (sin paginar por ahora)
		const resRecent = await event.fetch('/api/me/tasks?limit=20&status=recent', {
			headers: { 'cache-control': 'no-store' }
		});
		if (resRecent.ok) {
			const jsonRecent = await resRecent.json();
			recentTasks = Array.isArray(jsonRecent?.items) ? jsonRecent.items : [];
		}

		// Overview: obtener "sin responsable" de todos los grupos en una sola llamada
		const overviewOrder = order === 'group' ? 'group_then_due' : 'due';
		const resOverview = await event.fetch(
			`/api/me/tasks/overview?order=${encodeURIComponent(overviewOrder)}`,
			{ headers: { 'cache-control': 'no-store' } }
		);
		if (resOverview.ok) {
			const jsonOv = await resOverview.json();
			const items: any[] = Array.isArray(jsonOv?.unassigned) ? jsonOv.unassigned : [];
			unassignedOpen = items.map((it) => ({
				id: Number(it.id),
				description: String(it.description || ''),
				due_date: it.due_date ? String(it.due_date) : null,
				group_id: it.group_id ? String(it.group_id) : null,
				display_code: it.display_code != null ? Number(it.display_code) : null,
				assignees: Array.isArray(it.assignees) ? it.assignees.map(String) : []
			}));
		}

		// Mis grupos (para nombres y para recolectar "sin responsable")
		const resGroups = await event.fetch('/api/me/groups', {
			headers: { 'cache-control': 'no-store' }
		});
		if (resGroups.ok) {
			const jsonGroups = await resGroups.json();
			const groups = Array.isArray(jsonGroups?.items) ? jsonGroups.items : [];
			for (const g of groups) {
				const gid = String(g.id);
				const gname = g.name != null ? String(g.name) : null;
				if (gname) groupNames[gid] = gname;
			}
		}

	} catch {
		// Ignorar errores y dejar listas vacías
	}

	return {
		userId,
		openTasks,
		recentTasks,
		unassignedOpen,
		groupNames,
		order,
		page,
		hasMore
	};
};
