import { fetchWithAuth } from "./client";

export interface CreateBrandPayload {
  name: string;
  aliases?: string[];
  website?: string | null;
  industry?: string | null;
  platforms?: string[];
  frequency?: string;
}

export interface UpdateBrandPayload {
  name?: string;
  aliases?: string[];
  website?: string | null;
  industry?: string | null;
  platforms?: string[];
  frequency?: string;
  status?: string;
}

export interface AddCompetitorPayload {
  competitor_brand_id?: string;
  competitor_name?: string;
  name?: string;
  aliases?: string[];
}

function buildQuery(params: Record<string, string | number | boolean | undefined>): string {
  const qs = Object.entries(params)
    .filter(([, v]) => v !== undefined)
    .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`)
    .join("&");
  return qs ? `?${qs}` : "";
}

export const brandsApi = {
  /** 获取品牌列表 */
  list: (token: string, params?: { limit?: number; offset?: number }) =>
    fetchWithAuth(`/api/v1/brands/${buildQuery(params || {})}`, {}, token),

  /** 创建品牌 */
  create: (token: string, data: CreateBrandPayload) =>
    fetchWithAuth("/api/v1/brands/", { method: "POST", body: JSON.stringify(data) }, token),

  /** 更新品牌 */
  update: (token: string, brandId: string, data: UpdateBrandPayload) =>
    fetchWithAuth(
      `/api/v1/brands/${brandId}`,
      { method: "PUT", body: JSON.stringify(data) },
      token
    ),

  /** 删除品牌 */
  delete: (token: string, brandId: string) =>
    fetchWithAuth(`/api/v1/brands/${brandId}`, { method: "DELETE" }, token),

  /** 获取品牌详情 */
  getDetail: (token: string, brandId: string) =>
    fetchWithAuth(`/api/v1/brands/${brandId}`, {}, token),

  /** 立即查询品牌 */
  queryNow: (token: string, brandId: string) =>
    fetchWithAuth(`/api/v1/brands/${brandId}/query-now`, { method: "POST" }, token),

  /** 添加竞品 */
  addCompetitor: (token: string, brandId: string, data: AddCompetitorPayload) =>
    fetchWithAuth(
      `/api/v1/brands/${brandId}/competitors`,
      { method: "POST", body: JSON.stringify(data) },
      token
    ),

  /** 删除竞品 */
  deleteCompetitor: (token: string, brandId: string, competitorId: string) =>
    fetchWithAuth(
      `/api/v1/brands/${brandId}/competitors/${competitorId}`,
      { method: "DELETE" },
      token
    ),

  /** 获取竞品推荐 */
  getCompetitorRecommendations: (token: string, brandId: string) =>
    fetchWithAuth(`/api/v1/brands/${brandId}/competitor-recommendations`, {}, token),

  /** 获取品牌对比数据 */
  getCompare: (token: string, brandId: string) =>
    fetchWithAuth(`/api/v1/brands/${brandId}/compare`, {}, token),
};
