import { useQuery } from '@tanstack/react-query';
import { stockDataClient } from '@/client/api';
import { dateNotesClient } from '@/client/api';
import type { StockData, DateMemo } from '../types/index';
import type { InferResponseType } from 'hono/client';

// 定义响应类型
type StockHistoryResponse = InferResponseType<typeof stockDataClient.history[':code']['$get'], 200>;
type DateNotesListResponse = InferResponseType<typeof dateNotesClient.$get, 200>;

export function useStockQueries(code?: string) {
  // 查询股票历史数据
  const {
    data: stockDataResponse,
    isLoading: isLoadingStock,
    error: stockError,
    refetch: refetchStock
  } = useQuery({
    queryKey: ['stockHistory', code],
    queryFn: async (): Promise<StockHistoryResponse> => {
      if (!code) throw new Error('股票代码不能为空');
      const response = await stockDataClient.history[':code'].$get({
        param: { code }
      });
      if (!response.ok) {
        throw new Error('获取股票历史数据失败');
      }
      return response.json();
    },
    enabled: !!code,
    retry: 0,
  });

  // 查询备忘录数据
  const {
    data: memoDataResponse,
    isLoading: isLoadingMemo,
    error: memoError,
    refetch: refetchMemo
  } = useQuery({
    queryKey: ['memoData', code],
    queryFn: async (): Promise<DateNotesListResponse> => {
      const response = await dateNotesClient.$get({
        query: {
          filters: JSON.stringify(code ? { code } : {}),
          page: 1,
          pageSize: 1000
        }
      });
      if (!response.ok) {
        throw new Error('获取股票历史数据失败');
      }
      return response.json();
    },
    enabled: false,
  });

  // 转换数据格式 - API返回数字类型，转换为前端需要的字符串类型
  const stockData: StockData[] = (stockDataResponse?.data || []).map((item) => ({
    d: item.d,
    o: item.o.toString(),
    h: item.h.toString(),
    l: item.l.toString(),
    c: item.c.toString(),
    v: item.v.toString(),
    zd: item.zd.toString(),
    // 其他字段根据需要转换
  }));

  // 处理date-notes响应格式（通用CRUD返回 { data: [], pagination: {} }）
  const memoData: DateMemo[] = (memoDataResponse?.data || []).map(item => ({
    _id: item.id,
    代码: item.code,
    日期: item.noteDate,
    提示: item.note,
  }));

  const isLoading = isLoadingStock || isLoadingMemo;
  const error = stockError || memoError;

  // 提供一个函数来手动触发查询
  const fetchData = async () => {
    if (!code) return;
    await Promise.all([
      refetchStock(),
      refetchMemo()
    ]);
  };

  return {
    stockData,
    memoData,
    isLoading,
    error,
    fetchData,
  };
}