import type { PageServerLoad } from './$types';
import { createServerClient } from '$lib/graphql/client';
import { redirect, error } from '@sveltejs/kit';
import { ACCOUNT_QUERY, type AccountQueryResult } from '$lib/graphql/queries/account';

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

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

	const location = data.account.addresses.find((addr) => addr.id === params.location);

	if (!location) {
		throw error(404, 'Location not found');
	}

	return {
		account: data.account,
		location
	};
};
