/**
 * useReportPageData — Guest / User 리포트 페이지가 공통으로 쓰는 데이터 훅.
 *
 * 단순히 기존 `useReport` + `useEnrichment` 조합을 한 곳에 묶어
 * 페이지 wrapper 두 곳에서 동일한 코드를 반복하지 않도록 합니다.
 */
import { useMemo } from 'react';
import { useLocation } from 'react-router';
import type { MarketingReport } from '@/features/report/types/report';
import { useReport } from '@/features/report/hooks/useReport';
import { useEnrichment } from '@/features/channels/hooks/useEnrichment';

interface UseReportPageDataResult {
  data: MarketingReport | null;
  isLoading: boolean;
  error: string | null;
  enrichStatus: ReturnType<typeof useEnrichment>['status'];
  /** DB row 의 clinic_id — 게스트 페이지에서 워크스페이스 점프 버튼 노출에 사용 */
  clinicId: string | null;
}

export function useReportPageData(id: string | undefined): UseReportPageDataResult {
  const location = useLocation();
  const {
    data: baseData,
    isLoading,
    error,
    isEnriched,
    socialHandles: dbSocialHandles,
    clinicId,
  } = useReport(id);

  const enrichmentParams = useMemo(() => {
    if (!baseData || isEnriched) return null;

    const state = location.state as Record<string, unknown> | undefined;
    const metadata = state?.metadata as Record<string, unknown> | undefined;
    const stateSocialHandles = metadata?.socialHandles as Record<string, string | null> | undefined;

    const handles = stateSocialHandles || dbSocialHandles;

    const igHandles: string[] = Array.isArray(handles?.instagram)
      ? (handles.instagram.filter(Boolean) as string[])
      : handles?.instagram
        ? [handles.instagram as string]
        : [];

    const ytHandle = handles?.youtube || baseData.youtubeAudit?.handle || undefined;
    const fbHandle = handles?.facebook || undefined;

    return {
      reportId: baseData.id,
      clinicName: baseData.clinicSnapshot.name,
      instagramHandles: igHandles.length > 0 ? igHandles : undefined,
      youtubeChannelId: ytHandle || undefined,
      facebookHandle: fbHandle as string | undefined,
      address: baseData.clinicSnapshot.location || undefined,
    };
  }, [baseData, isEnriched, dbSocialHandles, location.state]);

  const { status: enrichStatus, enrichedReport } = useEnrichment(baseData, enrichmentParams);

  return {
    data: enrichedReport || baseData,
    isLoading,
    error,
    enrichStatus,
    clinicId,
  };
}
