import type { PageServerLoad } from './$types';
import { createServerClient } from '$lib/graphql/client';
import {
	PROJECTS_QUERY,
	PROJECT_STATUS_COUNTS_QUERY,
	type ProjectsQueryResult,
	type ProjectStatusCountsQueryResult,
	type WorkStatus
} from '$lib/graphql/queries/projects';

const DEFAULT_LIMIT = 20;

function getCurrentMonth(): string {
	const now = new Date();
	const year = now.getFullYear();
	const month = String(now.getMonth() + 1).padStart(2, '0');
	return `${year}-${month}`;
}

function getMonthDateRange(month: string): { dateFrom: string; dateTo: string } {
	const [year, monthNum] = month.split('-').map(Number);
	const firstDay = new Date(year, monthNum - 1, 1);
	const lastDay = new Date(year, monthNum, 0);

	const dateFrom = firstDay.toISOString().split('T')[0];
	const dateTo = lastDay.toISOString().split('T')[0];

	return { dateFrom, dateTo };
}

export const load: PageServerLoad = async ({ locals, parent, url }) => {
	const { user } = await parent();

	// Parse URL parameters
	const month = url.searchParams.get('month') || getCurrentMonth();
	const statusParam = url.searchParams.get('status');
	const status: WorkStatus | null = statusParam as WorkStatus | null;
	const page = parseInt(url.searchParams.get('page') || '1', 10);
	const limit = parseInt(url.searchParams.get('limit') || String(DEFAULT_LIMIT), 10);

	const { dateFrom, dateTo } = getMonthDateRange(month);
	const offset = (page - 1) * limit;

	if (!locals.cookie) {
		return {
			projects: { items: [], totalCount: 0, hasNextPage: false },
			statusCounts: { scheduled: 0, inProgress: 0, completed: 0, cancelled: 0 },
			month,
			status,
			page,
			limit
		};
	}

	const client = createServerClient(locals.cookie);

	// Build filter - everyone on team interface sees only their assigned work
	const filter: Record<string, unknown> = {
		dateFrom,
		dateTo,
		status,
		teamProfileId: user?.id
	};

	// Fetch both projects and status counts in parallel
	const [projectsResult, countsResult] = await Promise.all([
		client
			.query<ProjectsQueryResult>({
				query: PROJECTS_QUERY,
				variables: {
					filter,
					pagination: {
						offset,
						limit
					}
				}
			})
			.catch((err) => {
				console.error('Failed to fetch projects:', err);
				return { data: null };
			}),
		client
			.query<ProjectStatusCountsQueryResult>({
				query: PROJECT_STATUS_COUNTS_QUERY,
				variables: {
					dateFrom,
					dateTo,
					teamProfileId: user?.id
				}
			})
			.catch((err) => {
				console.error('Failed to fetch status counts:', err);
				return { data: null };
			})
	]);

	return {
		projects: projectsResult.data?.projects ?? { items: [], totalCount: 0, hasNextPage: false },
		statusCounts: countsResult.data?.projectStatusCounts ?? {
			scheduled: 0,
			inProgress: 0,
			completed: 0,
			cancelled: 0
		},
		month,
		status,
		page,
		limit
	};
};
