import axios from 'axios';
import { API_BASE_URL } from './apiConfig';

export interface MarketCount {
  market: string;
  count: number;
}

export interface TypeCount {
  candleTypeKey: string;
  count: number;
}

export interface CandleSeriesStats {
  market: string;
  candleType: string;
  unit: number | null;
  timeFrameLabel: string;
  minKst: string | null;
  maxKst: string | null;
  count: number;
}

export interface IngestionRow {
  sourceKey: string;
  market: string;
  unitPath: string;
  targetDate: string | null;
  status: string;
  fileHash: string | null;
  lastError: string | null;
  updatedAt: string | null;
}

export interface IngestionCountByStatus {
  status: string;
  count: number;
}

export interface WsSubRow {
  market: string;
  intervalCode: string;
  active: boolean;
}

export interface UpbitDbStatus {
  totalCandleRows: number;
  /** upbit_candles MAX(updated_at) — 총 행이 늘지 않아도 UPSERT 시 갱신됨 */
  candlesMaxUpdatedAt?: string | null;
  distinctMarketCount: number;
  fallbackToRest: string;
  candleRowsByMarket: MarketCount[];
  candleRowsByCandleType: TypeCount[];
  series: CandleSeriesStats[];
  recentIngestion: IngestionRow[];
  ingestionByStatus: IngestionCountByStatus[];
  tradeArchiveRows: number;
  wsSubscriptions: WsSubRow[];
}

export const upbitDbStatusApi = {
  getStatus: async (): Promise<UpbitDbStatus> => {
    const { data } = await axios.get<UpbitDbStatus>(`${API_BASE_URL}/upbit/db-status`);
    return data;
  },
};
