import type { PageServerLoad } from './$types';
import { createServerClient } from '$lib/graphql/client';
import { SERVICE_QUERY, type ServiceQueryResult } from '$lib/graphql/queries/services';
import { TEAM_PROFILES_QUERY, type TeamProfilesQueryResult } from '$lib/graphql/queries/team';
import {
	LATEST_SERVICE_SESSION_QUERY,
	type LatestServiceSessionQueryResult
} from '$lib/graphql/queries/session';
import { error, redirect } from '@sveltejs/kit';

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

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

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

	const client = createServerClient(locals.cookie);

	const [serviceResult, teamResult, sessionResult] = await Promise.all([
		client
			.query<ServiceQueryResult>({
				query: SERVICE_QUERY,
				variables: { id: params.service }
			})
			.catch((err) => {
				console.error('Failed to fetch service:', err);
				return { data: null };
			}),
		client
			.query<TeamProfilesQueryResult>({
				query: TEAM_PROFILES_QUERY
			})
			.catch((err) => {
				console.error('Failed to fetch team profiles:', err);
				return { data: null };
			}),
		client
			.query<LatestServiceSessionQueryResult>({
				query: LATEST_SERVICE_SESSION_QUERY,
				variables: { serviceId: params.service }
			})
			.catch((err) => {
				console.error('Failed to fetch session:', err);
				return { data: null };
			})
	]);

	if (!serviceResult.data?.service) {
		throw error(404, 'Service not found');
	}

	// Verify the user is assigned to this service (for TEAM_MEMBER role)
	const service = serviceResult.data.service;
	if (user.role === 'TEAM_MEMBER') {
		const isAssigned = service.teamMembers.some((m) => m.teamProfileId === user.id);
		if (!isAssigned) {
			throw error(403, 'You are not assigned to this service');
		}
	}

	return {
		service,
		teamProfiles: teamResult.data?.teamProfiles ?? [],
		session: sessionResult.data?.latestServiceSession ?? null
	};
};
