import { fetchWithAuth } from "./client";

export interface AttributionResponse {
  id: string;
  brand_id: string;
  content_id: string | null;
  baseline_score: number;
  current_score: number | null;
  score_delta: number | null;
  status: string;
  roi_percentage: number | null;
  created_at: string;
}

export interface BrandAttributionSummary {
  brand_id: string;
  records: AttributionResponse[];
  total_score_delta: number;
  tracking_count: number;
  completed_count: number;
  positive_count: number;
}

export interface ROIReport {
  brand_id: string;
  brand_name: string;
  subscription_cost: number;
  current_plan: string;
  total_score_delta: number;
  value_generated: number;
  roi_percentage: number;
  break_even_delta: number;
  tracking_records: AttributionResponse[];
  ab_comparison: ABComparison | null;
}

export interface ABComparison {
  overall_before: number;
  overall_after: number;
  overall_delta: number;
  dimensions: ABDimension[];
}

export interface ABDimension {
  name: string;
  before: number;
  after: number;
  delta: number;
  improved: boolean;
}

export interface ABComparisonResponse {
  brand_id: string;
  brand_name: string;
  overall_before: number;
  overall_after: number;
  overall_delta: number;
  dimensions: ABDimension[];
}

export const attributionApi = {
  startTracking: async (token: string, data: { brand_id: string; content_id?: string }) =>
    fetchWithAuth("/api/v1/attribution/start", {
      method: "POST",
      body: JSON.stringify(data),
    }, token) as Promise<AttributionResponse>,

  getBrandSummary: async (token: string, brandId: string) =>
    fetchWithAuth(`/api/v1/attribution/brand/${brandId}`, {}, token) as Promise<BrandAttributionSummary>,

  getRecord: async (token: string, recordId: string) =>
    fetchWithAuth(`/api/v1/attribution/${recordId}`, {}, token) as Promise<AttributionResponse>,

  checkAttribution: async (token: string, recordId: string) =>
    fetchWithAuth(`/api/v1/attribution/${recordId}/check`, {
      method: "POST",
    }, token) as Promise<AttributionResponse>,

  getROIReport: async (token: string, brandId: string) =>
    fetchWithAuth(`/api/v1/attribution/roi/${brandId}`, {}, token) as Promise<ROIReport>,

  getABComparison: async (token: string, brandId: string) =>
    fetchWithAuth(`/api/v1/attribution/ab-comparison/${brandId}`, {}, token) as Promise<ABComparisonResponse>,
};
