import { GetAccountStore } from '$houdini';
import { GetScopeTemplatesStore } from '$lib/utils/scopes';
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 { GetProductsDocument, type ProductEdge, type Product } from '$lib/graphql/wave/generated';
import type { PageServerLoad } from './$types';

export interface WaveProduct {
	id: string;
	name: string;
	description: string | null;
	unitPrice: number;
	isArchived: boolean;
}

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

	const result = await client.query(GetProductsDocument, {
		businessId: PUBLIC_WAVE_BUSINESS_ID,
		pageSize: 500,
		isSold: true,
		isArchived: false
	});

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

	const edges = result.data?.business?.products?.edges ?? [];
	return edges
		.filter((edge: ProductEdge): edge is ProductEdge & { node: Product } => edge.node != null)
		.map((edge: ProductEdge & { node: Product }) => ({
			id: edge.node.id,
			name: edge.node.name,
			description: edge.node.description ?? null,
			unitPrice: edge.node.unitPrice,
			isArchived: edge.node.isArchived
		}));
}

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

	const [account, scopeTemplates, waveProducts] = await Promise.all([
		new GetAccountStore().fetch({
			...fetchParams,
			variables: { id: event.params.account }
		}),
		new GetScopeTemplatesStore().fetch(fetchParams),
		fetchWaveProducts()
	]);

	return { account, scopeTemplates, waveProducts };
};
