import { defineStore } from "pinia";
import { ref } from "vue";

import { marketApi, type MarketSummary } from "../api/market";

function shanghaiDate(): string {
  return new Intl.DateTimeFormat("en-CA", {
    timeZone: "Asia/Shanghai",
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
  }).format(new Date());
}

export const useMarketStore = defineStore("market", () => {
  const selectedDate = ref(shanghaiDate());
  const summary = ref<MarketSummary | null>(null);
  const loading = ref(false);
  const error = ref("");

  async function load(date?: string): Promise<void> {
    loading.value = true;
    error.value = "";
    try {
      summary.value = await marketApi.summary(date);
      selectedDate.value = summary.value.context.actual_date ?? summary.value.context.requested_date;
    } catch (reason) {
      error.value = reason instanceof Error ? reason.message : "行情摘要读取失败";
    } finally {
      loading.value = false;
    }
  }

  async function selectDate(date: string): Promise<void> {
    await load(date);
  }

  async function moveDate(offset: number): Promise<void> {
    const date = new Date(`${selectedDate.value}T12:00:00+08:00`);
    date.setUTCDate(date.getUTCDate() + offset);
    await load(date.toISOString().slice(0, 10));
  }

  return { selectedDate, summary, loading, error, load, selectDate, moveDate };
});
