import { api } from "./client";

export type TradeContext = {
  requested_date: string;
  actual_date: string | null;
  previous_date: string | null;
  observed_at: string | null;
  state: "realtime" | "final" | "archive" | null;
  carried_forward: boolean;
  message: string;
};

export type MarketSummary = {
  context: TradeContext;
  values: Record<string, unknown> | null;
};

export type MarketEntity = {
  entity_type: "stock" | "sector" | "theme" | "index";
  identifier: string;
  code: string;
  name: string;
  sector: string | null;
};

export type SearchGroup = {
  entity_type: MarketEntity["entity_type"];
  label: string;
  items: MarketEntity[];
};

export type SearchResults = { query: string; groups: SearchGroup[] };

export type ChartPoint = {
  time: string;
  open: number;
  high: number;
  low: number;
  close: number;
  volume: number;
  amount: number;
  average: number | null;
};

export type ChartSeries = {
  entity_type: MarketEntity["entity_type"];
  identifier: string;
  code: string;
  name: string;
  interval: "day" | "minute";
  trade_date: string;
  observed_at: string;
  previous_close: number | null;
  range_start: string | null;
  range_end: string | null;
  points: ChartPoint[];
};

export type EntityMetric = { key: string; label: string; value: number | null; unit: string };
export type EntityDetail = {
  entity: MarketEntity;
  trade_date: string;
  observed_at: string;
  price: number;
  previous_close: number | null;
  change: number | null;
  metrics: EntityMetric[];
  money_flow: {
    available: boolean;
    net_million: number | null;
    large_million: number | null;
    net_5d_million: number | null;
    flow_to_circ_mv_5d: number | null;
  } | null;
  event: {
    status: string;
    reason: string;
    streak: number | null;
    first_time: string | null;
    last_time: string | null;
    open_times: number | null;
    seal_amount: number | null;
  } | null;
};

export type MarketWorkspaceData = {
  trade_date: string | null;
  observed_at?: string;
  carried_forward: boolean;
  message: string;
  overview: Record<string, number>;
  sentiment?: Record<string, unknown>;
  history?: Record<string, unknown>[];
  items?: Record<string, unknown>[];
};

export type RotationMembersData = {
  trade_date: string;
  sector_name: string;
  sector_code: string;
  member_count: number;
  quoted_count: number;
  coverage: number;
  items: Record<string, unknown>[];
};

export type MarketInsightData = MarketWorkspaceData & {
  requested_date: string;
  previous_date?: string;
  phase?: "pending" | "observing" | "selection" | "finalized" | "archive";
  current_available?: boolean;
  coverage?: number;
  summary: Record<string, unknown>;
  expectations?: Record<string, number>;
  themes?: { carry: Record<string, unknown>[]; new_themes: Record<string, unknown>[] };
  amount_history?: Record<string, unknown>[];
  focus_rows?: Record<string, unknown>[];
  rows?: Record<string, unknown>[];
  one_price_rows?: Record<string, unknown>[];
  watchlist_rows?: Record<string, unknown>[];
  watchlist_ready?: boolean;
  combined?: Record<string, unknown>[];
  ths?: Record<string, unknown>[];
  dc?: Record<string, unknown>[];
  status?: string;
  traders?: Record<string, unknown>[];
  operations?: Record<string, unknown>[];
  unclassified_seats?: Record<string, unknown>[];
  profiles?: Record<string, unknown>[];
};

export type ThemeDetailData = {
  trade_date: string;
  observed_at?: string;
  state?: string;
  message: string;
  theme: Record<string, unknown>;
  summary: Record<string, unknown>;
  members: Record<string, unknown>[];
};

export const marketApi = {
  summary(date?: string): Promise<MarketSummary> {
    const query = date ? `?date=${encodeURIComponent(date)}` : "";
    return api.get<MarketSummary>(`/market/summary${query}`);
  },
  search(query: string): Promise<SearchResults> {
    return api.get<SearchResults>(`/market/search?q=${encodeURIComponent(query)}`);
  },
  chart(entity: MarketEntity, interval: "day" | "minute"): Promise<ChartSeries> {
    const type = encodeURIComponent(entity.entity_type);
    const identifier = encodeURIComponent(entity.identifier);
    return api.get<ChartSeries>(`/market/entities/${type}/${identifier}/charts/${interval}`);
  },
  detail(entity: MarketEntity, date: string): Promise<EntityDetail> {
    const type = encodeURIComponent(entity.entity_type);
    const identifier = encodeURIComponent(entity.identifier);
    return api.get<EntityDetail>(`/market/entities/${type}/${identifier}/detail?date=${encodeURIComponent(date)}`);
  },
  workspace(key: string, date: string): Promise<MarketWorkspaceData> {
    return api.get<MarketWorkspaceData>(
      `/market/workspaces/${encodeURIComponent(key)}?date=${encodeURIComponent(date)}`,
    );
  },
  syncSnapshot(date: string): Promise<{ trade_date: string; temperature: number }> {
    return api.post(`/market/snapshot-sync?date=${encodeURIComponent(date)}`);
  },
  rotationMembers(sector: string, date: string): Promise<RotationMembersData> {
    return api.get<RotationMembersData>(
      `/market/rotation-members?sector=${encodeURIComponent(sector)}&date=${encodeURIComponent(date)}`,
    );
  },
  insight(key: string, date: string): Promise<MarketInsightData> {
    return api.get<MarketInsightData>(
      `/market/insights/${encodeURIComponent(key)}?date=${encodeURIComponent(date)}`,
    );
  },
  syncInsight(key: string, date: string): Promise<MarketInsightData> {
    return api.post<MarketInsightData>(
      `/market/insights/${encodeURIComponent(key)}/sync?date=${encodeURIComponent(date)}`,
    );
  },
  themeDetail(identifier: string, date: string): Promise<ThemeDetailData> {
    return api.get<ThemeDetailData>(
      `/market/themes/${encodeURIComponent(identifier)}?date=${encodeURIComponent(date)}`,
    );
  },
  saveSeatAlias(seat_name: string, alias_name: string): Promise<{ seat_name: string; alias_name: string }> {
    return api.put("/market/seat-aliases", { seat_name, alias_name });
  },
};
