"use client";

import { clientAuthFetch } from "@/app/utils/clientAuthFetch";
import { NEXT_PUBLIC_API_URL } from "@/config/api";
import {
  SETTING_DO_FLOOR_SUPPLIERS_2F,
  SETTING_DO_FLOOR_SUPPLIERS_4F,
} from "./constants";

const base = NEXT_PUBLIC_API_URL;

export type ShopComboRow = {
  id: number;
  code: string;
  name: string;
  value: number;
  label: string;
};

export type SettingsRow = {
  id: number;
  name: string;
  value: string;
  category?: string | null;
  type?: string | null;
};

async function parseJson<T>(res: Response): Promise<T> {
  if (!res.ok) {
    const t = await res.text().catch(() => "");
    throw new Error(t || `HTTP ${res.status}`);
  }
  return res.json() as Promise<T>;
}

/** 供應商列表：`GET /shop/combo/supplier` */
export async function fetchSupplierComboClient(): Promise<ShopComboRow[]> {
  const res = await clientAuthFetch(`${base}/shop/combo/supplier`, { method: "GET" });
  return parseJson<ShopComboRow[]>(res);
}

/** 店鋪列表：`GET /shop/combo/shop` */
export async function fetchShopComboClient(): Promise<ShopComboRow[]> {
  const res = await clientAuthFetch(`${base}/shop/combo/shop`, { method: "GET" });
  return parseJson<ShopComboRow[]>(res);
}

export async function fetchAllSettingsClient(): Promise<SettingsRow[]> {
  const res = await clientAuthFetch(`${base}/settings`, { method: "GET" });
  return parseJson<SettingsRow[]>(res);
}

export async function fetchDoFloorSettingsClient(): Promise<{
  suppliers2F: string;
  suppliers4F: string;
}> {
  const all = await fetchAllSettingsClient();
  const get = (name: string) => all.find((s) => s.name === name)?.value ?? "";
  return {
    suppliers2F: get(SETTING_DO_FLOOR_SUPPLIERS_2F),
    suppliers4F: get(SETTING_DO_FLOOR_SUPPLIERS_4F),
  };
}

export async function postSettingClient(name: string, value: string): Promise<void> {
  const res = await clientAuthFetch(`${base}/settings/${encodeURIComponent(name)}`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ value }),
  });
  if (!res.ok) {
    const t = await res.text().catch(() => "");
    throw new Error(t || `Failed to save setting: ${res.status}`);
  }
}