import { GetCustomerStore } from '$houdini';
import { WAVE_ACCESS_TOKEN } from '$env/static/private';
import { PUBLIC_WAVE_BUSINESS_ID } from '$env/static/public';
import { createWaveServerClient } from '$lib/graphql/wave/client';
import {
	GetCustomersDocument,
	type CustomerEdge,
	type Customer
} from '$lib/graphql/wave/generated';
import type { PageServerLoad } from './$types';

export interface WaveCustomer {
	id: string;
	name: string;
	email: string | null;
	address: {
		city: string | null;
		province: { code: string } | null;
	} | null;
	isArchived: boolean;
}

async function fetchWaveCustomers(): Promise<WaveCustomer[]> {
	const client = createWaveServerClient(WAVE_ACCESS_TOKEN);

	const result = await client.query(GetCustomersDocument, {
		businessId: PUBLIC_WAVE_BUSINESS_ID,
		pageSize: 500
	});

	if (result.error) {
		console.error('Wave API error:', result.error);
		return [];
	}

	const edges = result.data?.business?.customers?.edges ?? [];
	return edges
		.filter((edge: CustomerEdge): edge is CustomerEdge & { node: Customer } => edge.node != null)
		.map((edge: CustomerEdge & { node: Customer }) => ({
			id: edge.node.id,
			name: edge.node.name,
			email: edge.node.email ?? null,
			address: edge.node.address
				? {
						city: edge.node.address.city ?? null,
						province: edge.node.address.province ? { code: edge.node.address.province.code } : null
					}
				: null,
			isArchived: edge.node.isArchived
		}));
}

export const load: PageServerLoad = async (event) => {
	const fetchParams = {
		event,
		metadata: { cookie: event.locals.cookie }
	};

	// Fetch customer and Wave customers in parallel
	const [customer, waveCustomers] = await Promise.all([
		new GetCustomerStore().fetch({
			...fetchParams,
			variables: { id: event.params.customer }
		}),
		fetchWaveCustomers()
	]);

	return { customer, waveCustomers };
};
