import type { PageServerLoad } from './$types';
import { createServerClient } from '$lib/graphql/client';
import { ACCOUNTS_QUERY, type AccountsQueryResult } from '$lib/graphql/queries/accounts';
import { redirect } from '@sveltejs/kit';

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

	// Redirect if not authenticated or not a team member
	if (!user || user.__typename !== 'TeamProfileType') {
		throw redirect(303, '/');
	}

	if (!locals.cookie) {
		return { accounts: [] };
	}

	const client = createServerClient(locals.cookie);

	// For team members, we fetch all accounts but the backend should filter
	// based on their assignments. For now fetch all accounts.
	const { data } = await client
		.query<AccountsQueryResult>({
			query: ACCOUNTS_QUERY,
			variables: { filter: { status: 'ACTIVE' } }
		})
		.catch((err) => {
			console.error('Failed to fetch accounts:', err);
			return { data: null };
		});

	return { accounts: data?.accounts ?? [] };
};
