'use server';

import React from 'react';

import { AccountWithParams } from '@/packages/features/accounts/src/types/accounts';

import { getLatestResponseTime } from '~/lib/utils';

import { loadAnalyses } from '../../_lib/server/load-analyses';
import { loadRecommendations } from '../../_lib/server/load-recommendations';
import OrderAnalysesCards from '../order-analyses-cards';
import { AnalysisResponses } from './types';

export default async function Recommendations({
  account,
  analysisResponses,
}: {
  account: AccountWithParams;
  analysisResponses?: AnalysisResponses;
}) {
  const { analyses, countryCode } = await loadAnalyses();

  const currentAIResponseTimestamp = getLatestResponseTime(analysisResponses);
  const analysisRecommendations = await loadRecommendations({
    account,
    analyses,
    analysisResponses,
    aiResponseTimestamp: currentAIResponseTimestamp,
  });
  const orderAnalyses = analyses.filter((analysis) =>
    analysisRecommendations.includes(analysis.title),
  );

  if (orderAnalyses.length === 0) {
    return null;
  }

  return (
    <OrderAnalysesCards analyses={orderAnalyses} countryCode={countryCode} />
  );
}
