import { fetchWithAuth } from "./client";

export interface CreateQueryPayload {
  keyword: string;
  brand_id?: string;
  platforms?: string[];
  frequency?: string;
}

export interface UpdateQueryPayload {
  keyword?: string;
  platforms?: string[];
  frequency?: string;
  is_active?: boolean;
}

export interface ApiQueryItem {
  id: string;
  keyword: string;
  target_brand: string;
  brand_id?: string;
  brand_aliases?: string[];
  platforms: string[];
  frequency: string;
  is_active: boolean;
  status: string;
  last_queried_at: string | null;
  created_at: string;
}

export interface QueryListResponse {
  items: ApiQueryItem[];
  total: number;
}

export const queriesApi = {
  list: (token: string) => fetchWithAuth("/api/v1/queries/", {}, token) as Promise<QueryListResponse>,
  create: (token: string, data: CreateQueryPayload) =>
    fetchWithAuth(
      "/api/v1/queries/",
      { method: "POST", body: JSON.stringify(data) },
      token
    ) as Promise<ApiQueryItem>,
  update: (token: string, id: string, data: UpdateQueryPayload) =>
    fetchWithAuth(
      `/api/v1/queries/${id}`,
      { method: "PUT", body: JSON.stringify(data) },
      token
    ) as Promise<ApiQueryItem>,
  delete: (token: string, id: string) =>
    fetchWithAuth(`/api/v1/queries/${id}`, { method: "DELETE" }, token),
  runNow: (token: string, id: string) =>
    fetchWithAuth(`/api/v1/queries/${id}/run-now`, { method: "POST" }, token),
};
