import { fetchWithAuth } from "./client";

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 interface TrendInsightRequest {
  brand_id: string;
  period_days?: number;
  platforms?: string[];
  keywords?: string[];
}

export interface TrendInsight {
  id: string;
  brand_id: string;
  insight_type: string;
  data: Record<string, unknown>;
  recommendations: string[] | null;
  period_start: string | null;
  period_end: string | null;
  created_at: string;
}

export interface TrendInsightList {
  items: TrendInsight[];
  total: number;
}

export interface TrendInsightResponse extends TrendInsight {}

export interface TrendSummary {
  brand_id: string;
  period_days: number;
  trend_direction: string;
  hotspot_keywords: string[];
  platform_comparison: Record<string, unknown>;
}

export const trendsApi = {
  createInsight: (token: string, data: TrendInsightRequest) =>
    fetchWithAuth("/api/v1/trends/insight", {
      method: "POST",
      body: JSON.stringify(data),
    }, token) as Promise<TrendInsightResponse>,

  getBrandInsights: (token: string, brandId: string, params?: { skip?: number; limit?: number }) =>
    fetchWithAuth(
      `/api/v1/trends/brand/${brandId}${buildQuery(params || {})}`,
      {},
      token
    ) as Promise<TrendInsightList>,

  getSummary: (token: string, brandId: string, periodDays?: number) =>
    fetchWithAuth(
      `/api/v1/trends/brand/${brandId}/summary${buildQuery({ period_days: periodDays })}`,
      {},
      token
    ) as Promise<TrendSummary>,

  getInsight: (token: string, insightId: string) =>
    fetchWithAuth(`/api/v1/trends/${insightId}`, {}, token) as Promise<TrendInsightResponse>,
};
