import type { PageServerLoad } from './$types';
import { createServerClient } from '$lib/graphql/client';
import { PROJECT_QUERY, type ProjectQueryResult } from '$lib/graphql/queries/projects';
import { error } from '@sveltejs/kit';

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

	// Must be a customer profile
	if (!user || user.__typename !== 'CustomerProfileType') {
		throw error(403, 'Access denied');
	}

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

	const client = createServerClient(locals.cookie);

	const projectResult = await client
		.query<ProjectQueryResult>({
			query: PROJECT_QUERY,
			variables: { id: params.project }
		})
		.catch((err) => {
			console.error('Failed to fetch project:', err);
			return { data: null };
		});

	const project = projectResult.data?.project;

	if (!project) {
		throw error(404, 'Project not found');
	}

	// Verify customer has access to this project
	const customerIds = customers?.map((c: { id: string }) => c.id) ?? [];

	if (!project.customerId || !customerIds.includes(project.customerId)) {
		throw error(403, 'You do not have access to this project');
	}

	return {
		project
	};
};
