/**
 * 营业日配置全局状态 — Zustand store。
 *
 * - 启动时请求一次 /api/config/business-day
 * - API 不可用时降级为默认值 8，console.warn 输出警告
 */

import { create } from "zustand";
import { fetchBusinessDayConfig } from "../api/businessDay";

const DEFAULT_START_HOUR = 8;

export interface BusinessDayState {
  /** 营业日分割点小时值（0–23） */
  startHour: number;
  /** 是否已完成加载（含降级） */
  loaded: boolean;

  /** 启动时调用一次，从后端获取配置 */
  init: () => Promise<void>;
}

export const useBusinessDayStore = create<BusinessDayState>((set, get) => ({
  startHour: DEFAULT_START_HOUR,
  loaded: false,

  async init() {
    // 避免重复请求
    if (get().loaded) return;
    try {
      const config = await fetchBusinessDayConfig();
      set({ startHour: config.business_day_start_hour, loaded: true });
    } catch {
      console.warn(
        "[BusinessDay] 无法获取营业日配置，使用默认值:",
        DEFAULT_START_HOUR,
      );
      set({ startHour: DEFAULT_START_HOUR, loaded: true });
    }
  },
}));
