import { cache } from 'react';

import { createUserAnalysesApi } from '@/packages/features/user-analyses/src/server/api';
import type { AnalysisResultDetailsMapped } from '@/packages/features/user-analyses/src/types/analysis-results';

import { getSupabaseServerClient } from '@kit/supabase/server-client';

export type UserAnalyses = Awaited<ReturnType<typeof loadUserAnalysis>>;

/**
 * @name loadUserAnalysis
 * @description
 * Load the user's analysis based on id. It's a cached per-request function that fetches the user's analysis data.
 */
export const loadUserAnalysis = cache(analysisLoader);

async function analysisLoader(
  analysisOrderId: number,
): Promise<AnalysisResultDetailsMapped | null> {
  const client = getSupabaseServerClient();
  const api = createUserAnalysesApi(client);

  return api.getUserAnalysis(analysisOrderId);
}
