import { axiosInstance } from './client';
import type {
  RevenueLeak,
  RevenueLeakCreate,
  RevenueLeakUpdate,
  ScanResult,
  RemediationResponse,
  ResolutionHistoryResponse,
  RecurringLeaksResponse,
  StatsResponse,
  SeverityRulesResponse,
  AlertSettingsResponse,
  SeverityRule,
  AlertSettings,
} from '../types';

const baseUrl = '/api/company';

export async function getRevenueLeaks(
  companyId: string,
  params?: { severity?: string; resolved?: string }
): Promise<RevenueLeak[]> {
  const response = await axiosInstance.get(`${baseUrl}/${companyId}/revenue-leaks`, { params });
  return response.data.revenue_leaks;
}

export async function createRevenueLeak(
  companyId: string,
  data: RevenueLeakCreate
): Promise<RevenueLeak> {
  const response = await axiosInstance.post(`${baseUrl}/${companyId}/revenue-leaks`, data);
  return response.data.revenue_leak;
}

export async function updateRevenueLeak(
  companyId: string,
  leakId: string,
  data: RevenueLeakUpdate
): Promise<RevenueLeak> {
  const response = await axiosInstance.put(`${baseUrl}/${companyId}/revenue-leaks/${leakId}`, data);
  return response.data.revenue_leak;
}

export async function deleteRevenueLeak(
  companyId: string,
  leakId: string
): Promise<{ success: boolean }> {
  const response = await axiosInstance.delete(`${baseUrl}/${companyId}/revenue-leaks/${leakId}`);
  return response.data;
}

export async function resolveRevenueLeak(
  companyId: string,
  leakId: string,
  resolutionNotes?: string
): Promise<RevenueLeak> {
  const response = await axiosInstance.patch(
    `${baseUrl}/${companyId}/revenue-leaks/${leakId}/resolve`,
    resolutionNotes ? { resolution_notes: resolutionNotes } : {}
  );
  return response.data.revenue_leak;
}

// ---- Phase 4 API calls ----

export async function scanLeaks(
  companyId: string,
  detectorIds?: string[]
): Promise<ScanResult> {
  const response = await axiosInstance.post(
    `${baseUrl}/${companyId}/revenue-leaks/scan`,
    detectorIds ? { detectors: detectorIds } : {}
  );
  return response.data;
}

export async function getRemediation(
  companyId: string,
  leakId: string
): Promise<RemediationResponse> {
  const response = await axiosInstance.get(
    `${baseUrl}/${companyId}/revenue-leaks/${leakId}/remediation`
  );
  return response.data;
}

export async function applyRemediation(
  companyId: string,
  leakId: string,
  suggestionIndex: number
): Promise<{ success: boolean; optimization_move_id: number; suggestion: unknown }> {
  const response = await axiosInstance.post(
    `${baseUrl}/${companyId}/revenue-leaks/${leakId}/remediation`,
    { suggestion_index: suggestionIndex }
  );
  return response.data;
}

export async function getResolutionHistory(
  companyId: string,
  leakId: string
): Promise<ResolutionHistoryResponse> {
  const response = await axiosInstance.get(
    `${baseUrl}/${companyId}/revenue-leaks/${leakId}/resolution-history`
  );
  return response.data;
}

export async function getRecurringLeaks(
  companyId: string,
  days = 90
): Promise<RecurringLeaksResponse> {
  const response = await axiosInstance.get(
    `${baseUrl}/${companyId}/revenue-leaks/recurring`,
    { params: { days } }
  );
  return response.data;
}

export async function getResolutionStats(
  companyId: string,
  days = 30
): Promise<StatsResponse> {
  const response = await axiosInstance.get(
    `${baseUrl}/${companyId}/revenue-leaks/stats`,
    { params: { days } }
  );
  return response.data;
}

export async function getSeverityRules(
  companyId: string
): Promise<SeverityRulesResponse> {
  const response = await axiosInstance.get(
    `${baseUrl}/${companyId}/leak-settings/severity`
  );
  return response.data;
}

export async function updateSeverityRules(
  companyId: string,
  severityRules: SeverityRule[]
): Promise<SeverityRulesResponse> {
  const response = await axiosInstance.put(
    `${baseUrl}/${companyId}/leak-settings/severity`,
    { severity_rules: severityRules }
  );
  return response.data;
}

export async function getAlertSettings(
  companyId: string
): Promise<AlertSettingsResponse> {
  const response = await axiosInstance.get(
    `${baseUrl}/${companyId}/leak-settings/alerts`
  );
  return response.data;
}

export async function updateAlertSettings(
  companyId: string,
  data: Partial<AlertSettings>
): Promise<AlertSettingsResponse> {
  const response = await axiosInstance.put(
    `${baseUrl}/${companyId}/leak-settings/alerts`,
    data
  );
  return response.data;
}

// ---- Multi-Location Rollup (P4) API calls ----

export async function getLocationRollup(
  days = 90
): Promise<import('../types').LocationLocationsResponse> {
  const response = await axiosInstance.get('/api/analytics/locations', {
    params: { period_days: days },
  });
  return response.data;
}

export async function getLocationComparison(
  days = 90
): Promise<import('../types').LocationComparisonResponse> {
  const response = await axiosInstance.get('/api/analytics/locations/comparison', {
    params: { period_days: days },
  });
  return response.data;
}

export async function runLocationDetector(
  params: { period_days?: number; min_variance_pct?: number; concentration_pct?: number }
): Promise<import('../types').LocationDetectorResponse> {
  const response = await axiosInstance.post('/api/analytics/locations/detector', params);
  return response.data;
}