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 MonitoringRecordCreate {
  brand_id: string;
  content_id?: string;
  query_keywords: string;
  platform?: string;
  check_interval_hours?: number;
}

export interface MonitoringRecord {
  id: string;
  brand_id: string;
  content_id: string | null;
  query_keywords: string;
  platform: string | null;
  baseline_citation_count: number;
  baseline_sentiment: number | null;
  baseline_rank: number | null;
  current_citation_count: number | null;
  current_sentiment: number | null;
  current_rank: number | null;
  change_type: string | null;
  change_details: Record<string, unknown> | null;
  check_interval_hours: number;
  last_checked_at: string | null;
  next_check_at: string | null;
  status: string;
  created_at: string;
  updated_at: string;
}

export interface MonitoringRecordList {
  records: MonitoringRecord[];
  total: number;
}

export interface MonitoringChangeReport {
  monitoring_record_id: string;
  brand_id: string;
  change_type: string;
  change_details: Record<string, unknown>;
  baseline: Record<string, unknown>;
  current: Record<string, unknown>;
  recommendations: string[];
}

export interface MonitoringStatusUpdate {
  status: string;
}

export interface MonitoringRecordResponse extends MonitoringRecord {}

export const monitoringApi = {
  createTask: (token: string, data: MonitoringRecordCreate) =>
    fetchWithAuth("/api/v1/monitoring/tasks", {
      method: "POST",
      body: JSON.stringify(data),
    }, token) as Promise<MonitoringRecordResponse>,

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

  getReport: (token: string, recordId: string) =>
    fetchWithAuth(`/api/v1/monitoring/${recordId}/report`, {}, token) as Promise<MonitoringChangeReport>,

  updateStatus: (token: string, recordId: string, data: MonitoringStatusUpdate) =>
    fetchWithAuth(`/api/v1/monitoring/${recordId}/status`, {
      method: "PUT",
      body: JSON.stringify(data),
    }, token) as Promise<MonitoringRecordResponse>,

  triggerCheck: (token: string, recordId: string) =>
    fetchWithAuth(`/api/v1/monitoring/${recordId}/check`, {
      method: "POST",
    }, token) as Promise<MonitoringRecordResponse>,
};
