import type { LayoutServerLoad } from './$types';
import { redirect, error } from '@sveltejs/kit';
import { client } from '$lib/graphql/client';
import { SERVICES_QUERY, type ServicesQueryResult } from '$lib/graphql/queries/services';
import { PROJECTS_QUERY, type ProjectsQueryResult } from '$lib/graphql/queries/projects';
import { INVOICES_QUERY, type InvoicesQueryResult } from '$lib/graphql/queries/invoices';
import { getCurrentMonth, getMonthDateRange } from '$lib/utils/date';

export const load: LayoutServerLoad = async ({ url, parent, locals }) => {
	const parentData = await parent();
	const me = parentData.user;

	// Not authenticated
	if (!me) {
		const returnTo = encodeURIComponent(url.pathname + url.search);
		throw redirect(307, `/login?return_to=${returnTo}`);
	}

	// Admin requires team profile with admin or team_leader role
	if (me.__typename !== 'TeamProfileType') {
		throw error(403, 'Admin access requires a team profile');
	}

	if (me.role !== 'ADMIN' && me.role !== 'TEAM_LEADER') {
		throw error(403, 'Admin access requires an admin or team leader role');
	}

	// Get month from URL params or default to current
	const month = url.searchParams.get('month') ?? getCurrentMonth();
	const { start, end } = getMonthDateRange(month);

	// Fetch services, projects, and invoices for the month in parallel
	const [servicesResult, projectsResult, invoicesResult] = await Promise.all([
		client.query<ServicesQueryResult>({
			query: SERVICES_QUERY,
			variables: {
				filter: { dateFrom: start, dateTo: end },
				pagination: { limit: 100 }
			},
			context: { headers: { cookie: locals.cookie } },
			fetchPolicy: 'network-only'
		}),
		client.query<ProjectsQueryResult>({
			query: PROJECTS_QUERY,
			variables: {
				filter: { dateFrom: start, dateTo: end },
				pagination: { limit: 100 }
			},
			context: { headers: { cookie: locals.cookie } },
			fetchPolicy: 'network-only'
		}),
		client.query<InvoicesQueryResult>({
			query: INVOICES_QUERY,
			variables: {
				pagination: { limit: 100 }
			},
			context: { headers: { cookie: locals.cookie } },
			fetchPolicy: 'network-only'
		})
	]);

	const services = servicesResult.data?.services?.items ?? [];
	const projects = projectsResult.data?.projects?.items ?? [];
	const invoices = invoicesResult.data?.invoices?.items ?? [];

	// Build lookup maps for quick access
	const accountLookup = new Map<string, { accountName: string; addressName: string }>();
	const customerLookup = new Map<string, { customerName: string }>();

	// Populate lookups from services
	for (const service of services) {
		if (service.accountAddressId && service.account) {
			accountLookup.set(service.accountAddressId, {
				accountName: service.account.name,
				addressName: service.accountAddress?.name || service.accountAddress?.city || 'Unknown'
			});
		}
	}

	// Populate lookups from projects
	for (const project of projects) {
		if (project.customer) {
			customerLookup.set(project.customerId, {
				customerName: project.customer.name
			});
		}
		if (project.accountAddressId && project.accountAddress) {
			accountLookup.set(project.accountAddressId, {
				accountName: project.accountAddress.account?.name || 'Unknown',
				addressName: project.accountAddress.name || project.accountAddress.city || 'Unknown'
			});
		}
	}

	// Populate lookups from invoices
	for (const invoice of invoices) {
		if (invoice.customer) {
			customerLookup.set(invoice.customerId, {
				customerName: invoice.customer.name
			});
		}
	}

	return {
		...parentData,
		services: {
			scheduled: services.filter((s) => s.status === 'SCHEDULED'),
			inProgress: services.filter((s) => s.status === 'IN_PROGRESS'),
			completed: services.filter((s) => s.status === 'COMPLETED')
		},
		projects: {
			scheduled: projects.filter((p) => p.status === 'SCHEDULED'),
			inProgress: projects.filter((p) => p.status === 'IN_PROGRESS'),
			completed: projects.filter((p) => p.status === 'COMPLETED')
		},
		invoices,
		accountLookup,
		customerLookup,
		currentMonth: month
	};
};
