import type { PageServerLoad } from './$types';
import { createServerClient } from '$lib/graphql/client';
import { redirect, error } from '@sveltejs/kit';
import { CUSTOMER_QUERY, type CustomerQueryResult } from '$lib/graphql/queries/customer';

export const load: PageServerLoad = async ({ locals, parent, params }) => {
	const { user } = await parent();

	// Redirect if not authenticated or not an admin/team leader
	if (
		!user ||
		user.__typename !== 'TeamProfileType' ||
		(user.role !== 'ADMIN' && user.role !== 'TEAM_LEADER')
	) {
		throw redirect(303, '/');
	}

	if (!locals.cookie) {
		throw error(401, 'Not authenticated');
	}

	const client = createServerClient(locals.cookie);

	const { data } = await client
		.query<CustomerQueryResult>({
			query: CUSTOMER_QUERY,
			variables: { id: params.customer }
		})
		.catch((err) => {
			console.error('Failed to fetch customer:', err);
			throw error(500, 'Failed to load customer');
		});

	if (!data?.customer) {
		throw error(404, 'Customer not found');
	}

	return {
		customer: data.customer,
		contacts: data.customer.contacts,
		addresses: data.customer.addresses,
		accounts: data.customer.accounts
	};
};
