import type { PageServerLoad } from './$types';
import { createServerClient } from '$lib/graphql/client';
import { redirect, error } from '@sveltejs/kit';
import {
	CUSTOMER_PROFILE_QUERY,
	type CustomerProfileQueryResult
} from '$lib/graphql/queries/customerProfile';

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<CustomerProfileQueryResult>({
			query: CUSTOMER_PROFILE_QUERY,
			variables: { id: params.profile }
		})
		.catch((err) => {
			console.error('Failed to fetch customer profile:', err);
			throw error(500, 'Failed to load customer profile');
		});

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

	return {
		profile: data.customerProfile
	};
};
