import type { LayoutServerLoad } from './$types';
import { redirect, error } from '@sveltejs/kit';
import { createServerClient } 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 { CUSTOMER_QUERY, type CustomerQueryResult } from '$lib/graphql/queries/customer';
import { getCurrentMonth, getMonthDateRange } from '$lib/utils/date';

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

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

	// Must be a CustomerProfileType
	if (user.__typename !== 'CustomerProfileType') {
		throw error(403, 'This area is only accessible to customers');
	}

	if (!locals.cookie) {
		return {
			...parentData,
			customers: [],
			accounts: [],
			services: { scheduled: [], inProgress: [], completed: [] },
			projects: { scheduled: [], inProgress: [], completed: [] }
		};
	}

	const client = createServerClient(locals.cookie);

	// Get assigned customer IDs
	const customerIds = user.customers?.map((c) => c.id) ?? [];

	// Fetch full customer data for each assigned customer
	const customersData = await Promise.all(
		customerIds.map(async (id) => {
			const result = await client
				.query<CustomerQueryResult>({
					query: CUSTOMER_QUERY,
					variables: { id }
				})
				.catch((err) => {
					console.error(`Failed to fetch customer ${id}:`, err);
					return { data: null };
				});
			return result.data?.customer ?? null;
		})
	);

	const customers = customersData.filter((c) => c !== null);

	// Flatten all accounts from all customers
	const accounts = customers.flatMap((customer) =>
		(customer.accounts ?? []).map((account) => ({
			...account,
			customerName: customer.name,
			customerId: customer.id
		}))
	);

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

	// Build filters for services and projects
	const filter = {
		dateFrom: start,
		dateTo: end,
		customerIds: customerIds.length > 0 ? customerIds : undefined
	};

	// Fetch services and projects
	const [servicesResult, projectsResult] = await Promise.all([
		client
			.query<ServicesQueryResult>({
				query: SERVICES_QUERY,
				variables: { filter, pagination: { limit: 100 } }
			})
			.catch((err) => {
				console.error('Failed to fetch services:', err);
				return { data: null };
			}),
		client
			.query<ProjectsQueryResult>({
				query: PROJECTS_QUERY,
				variables: { filter, pagination: { limit: 100 } }
			})
			.catch((err) => {
				console.error('Failed to fetch projects:', err);
				return { data: null };
			})
	]);

	const allServices = servicesResult.data?.services?.items ?? [];
	const allProjects = projectsResult.data?.projects?.items ?? [];

	return {
		...parentData,
		customers,
		accounts,
		services: {
			scheduled: allServices.filter((s) => s.status === 'SCHEDULED'),
			inProgress: allServices.filter((s) => s.status === 'IN_PROGRESS'),
			completed: allServices.filter((s) => s.status === 'COMPLETED')
		},
		projects: {
			scheduled: allProjects.filter((p) => p.status === 'SCHEDULED'),
			inProgress: allProjects.filter((p) => p.status === 'IN_PROGRESS'),
			completed: allProjects.filter((p) => p.status === 'COMPLETED')
		},
		currentMonth: month
	};
};
