import type { PageServerLoad } from './$types';
import { createServerClient } from '$lib/graphql/client';
import {
	SERVICES_FOR_ASSIGNMENT_QUERY,
	type ServicesForAssignmentQueryResult
} from '$lib/graphql/queries/services';
import { TEAM_PROFILES_QUERY, type TeamProfilesQueryResult } from '$lib/graphql/queries/team';
import { redirect } from '@sveltejs/kit';

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();

	// Redirect if not authenticated or not an admin/team leader
	if (
		!user ||
		user.__typename !== 'TeamProfileType' ||
		(user.role !== 'ADMIN' && user.role !== 'TEAM_LEADER')
	) {
		throw redirect(303, '/');
	}

	// Parse URL parameters
	const month = url.searchParams.get('month') || getCurrentMonth();
	const { dateFrom, dateTo } = getMonthDateRange(month);

	if (!locals.cookie) {
		return {
			services: { unassigned: [], readyToAssign: [], assigned: [] },
			teamProfiles: [],
			month
		};
	}

	const client = createServerClient(locals.cookie);

	// Fetch services for assignment and team profiles in parallel
	const [servicesResult, teamResult] = await Promise.all([
		client
			.query<ServicesForAssignmentQueryResult>({
				query: SERVICES_FOR_ASSIGNMENT_QUERY,
				variables: { dateFrom, dateTo }
			})
			.catch((err) => {
				console.error('Failed to fetch services for assignment:', err);
				return { data: null };
			}),
		client
			.query<TeamProfilesQueryResult>({
				query: TEAM_PROFILES_QUERY
			})
			.catch((err) => {
				console.error('Failed to fetch team profiles:', err);
				return { data: null };
			})
	]);

	// Filter to only active non-admin team members for assignment
	const teamProfiles =
		teamResult.data?.teamProfiles.filter((p) => p.status === 'ACTIVE' && p.role !== 'ADMIN') ?? [];

	return {
		services: servicesResult.data?.servicesForAssignment ?? {
			unassigned: [],
			readyToAssign: [],
			assigned: []
		},
		teamProfiles,
		month,
		currentUserProfileId: user.id
	};
};
