import type { LayoutServerLoad } from './$types';
import { redirect, error } from '@sveltejs/kit';
import { CustomerAccountsStore, CustomerDashboardStore } from '$houdini';
import { fromGlobalId } from '$lib/utils/relay';
import { getCurrentMonth } from '$lib/utils/date';

export interface CustomerAccountInfo {
	name: string;
	addressName?: string;
	streetAddress?: string;
	city?: string;
	state?: string;
}

export const load: LayoutServerLoad = async (event) => {
	const { url, parent, locals, depends } = event;
	depends('app:dashboard');

	const parentData = await parent();

	// Get month from URL params or default to current month
	const currentMonth = url.searchParams.get('month') ?? getCurrentMonth();
	const me = parentData.user?.data?.me;

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

	// Customer routes require customer profile
	if (me.__typename !== 'CustomerProfileType') {
		throw error(403, 'This area is only accessible to customers');
	}

	// Get customer UUIDs from profile
	const customerIds = me.customers?.map((c) => fromGlobalId(c.id)) ?? [];

	if (customerIds.length === 0) {
		// Customer profile has no linked customers - show empty state
		return {
			...parentData,
			currentMonth,
			customerIds: [],
			customerNames: {} as Record<string, string>,
			customerAccountLookup: {} as Record<string, CustomerAccountInfo>,
			accounts: [],
			services: {
				upcoming: [],
				completed: []
			},
			projects: {
				upcoming: [],
				completed: []
			},
			invoices: []
		};
	}

	// Build customer name lookup
	const customerNames = new Map<string, string>();
	me.customers?.forEach((c) => {
		customerNames.set(fromGlobalId(c.id), c.name);
	});

	const fetchParams = { event, metadata: { cookie: locals.cookie } };

	// Fetch accounts and dashboard data in parallel
	// Need accounts for display lookup, dashboard for services/projects/invoices
	const [accountsResults, dashboardResults] = await Promise.all([
		// Fetch accounts for all linked customers
		Promise.all(
			customerIds.map((customerId) =>
				new CustomerAccountsStore().fetch({
					...fetchParams,
					variables: { filters: { customerId } }
				})
			)
		),
		// Fetch consolidated dashboard data for each customer
		Promise.all(
			customerIds.map((customerId) =>
				new CustomerDashboardStore().fetch({
					...fetchParams,
					variables: { customerId }
				})
			)
		)
	]);

	// Combine all accounts from all customers
	const allAccounts = accountsResults.flatMap((result) => result.data?.accounts ?? []);

	// Combine dashboard data from all customers
	const allServices = dashboardResults.flatMap(
		(result) => result.data?.customerDashboard?.services ?? []
	);
	const allProjects = dashboardResults.flatMap(
		(result) => result.data?.customerDashboard?.projects ?? []
	);
	const allInvoices = dashboardResults.flatMap(
		(result) => result.data?.customerDashboard?.invoices ?? []
	);

	// Build account lookup for display
	const customerAccountLookup = new Map<string, CustomerAccountInfo>();

	allAccounts.forEach((account) => {
		const accountUuid = fromGlobalId(account.id);
		customerAccountLookup.set(accountUuid, {
			name: account.name,
			streetAddress: account.primaryAddress?.streetAddress,
			city: account.primaryAddress?.city,
			state: account.primaryAddress?.state
		});
		// Also map addresses
		account.addresses?.forEach((addr) => {
			const addrUuid = fromGlobalId(addr.id);
			customerAccountLookup.set(addrUuid, {
				name: account.name,
				addressName: addr.name,
				streetAddress: addr.streetAddress,
				city: addr.city,
				state: addr.state
			});
		});
	});

	// Filter services by status
	const upcomingServices = allServices.filter(
		(s) => s.status === 'SCHEDULED' || s.status === 'IN_PROGRESS'
	);
	const completedServices = allServices.filter((s) => s.status === 'COMPLETED');

	// Filter projects by status
	const upcomingProjects = allProjects.filter(
		(p) => p.status === 'SCHEDULED' || p.status === 'IN_PROGRESS'
	);
	const completedProjects = allProjects.filter((p) => p.status === 'COMPLETED');

	return {
		...parentData,
		currentMonth,
		customerIds,
		customerNames: Object.fromEntries(customerNames),
		customerAccountLookup: Object.fromEntries(customerAccountLookup),
		accounts: allAccounts,
		services: {
			upcoming: upcomingServices,
			completed: completedServices
		},
		projects: {
			upcoming: upcomingProjects,
			completed: completedProjects
		},
		invoices: allInvoices
	};
};
