import type { CandleData } from '../services/backtestApi';

/**
 * 차트 캔들 time 필드 → Unix ms.
 * REST/내부에서 toISOString() 후 'Z'를 뺀 문자열은 UTC로 해석해야 Upbit WS·alignSec와 일치함.
 */
export function parseChartCandleTimeToUnixMs(c: CandleData | undefined): number {
  if (!c || c.time == null || (typeof c.time === 'string' && c.time.trim() === '')) return 0;
  const t = c.time as string | number;
  if (typeof t === 'number') {
    return t > 1e12 ? t : t * 1000;
  }
  const s = String(t).trim();
  if (!s) return 0;
  if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(s) && !/[zZ]|[+-]\d{2}:?\d{2}$/.test(s)) {
    const ms = Date.parse(`${s}Z`);
    if (Number.isFinite(ms)) return ms;
  }
  const ms = Date.parse(s);
  return Number.isFinite(ms) ? ms : 0;
}

/** 단일 time 값 → Unix 초 (메인 buildCandleDataRaw / updateLastCandle / 보조지표 toUnix 공통) */
export function chartTimeValueToUnixSeconds(v: string | number | undefined | null): number | null {
  if (v == null || v === '') return null;
  if (typeof v === 'number') {
    if (!isFinite(v)) return null;
    return Math.floor(v >= 1e12 ? v / 1000 : v);
  }
  const ms = parseChartCandleTimeToUnixMs({ time: v } as CandleData);
  if (!ms) return null;
  return Math.floor(ms / 1000);
}
