/**
 * Sustainability API Service
 * Environmental impact, SDG compliance, and grant reporting
 */

import apiClient from '../client/apiClient';
import type {
  SustainabilityMetrics,
  SustainabilityWidgetData,
  SDGCompliance,
  EnvironmentalImpact,
  GrantReport
} from '../types/sustainability';

const BASE_PATH = '/sustainability';

/**
 * Get comprehensive sustainability metrics
 */
export async function getSustainabilityMetrics(
  tenantId: string,
  startDate?: string,
  endDate?: string
): Promise<SustainabilityMetrics> {
  const params = new URLSearchParams();
  if (startDate) params.append('start_date', startDate);
  if (endDate) params.append('end_date', endDate);

  const queryString = params.toString();
  const url = `/tenants/${tenantId}${BASE_PATH}/metrics${queryString ? `?${queryString}` : ''}`;

  return await apiClient.get<SustainabilityMetrics>(url);
}

/**
 * Get simplified sustainability widget data
 */
export async function getSustainabilityWidgetData(
  tenantId: string,
  days: number = 30
): Promise<SustainabilityWidgetData> {
  return await apiClient.get<SustainabilityWidgetData>(
    `/tenants/${tenantId}${BASE_PATH}/widget?days=${days}`
  );
}

/**
 * Get SDG 12.3 compliance status
 */
export async function getSDGCompliance(tenantId: string): Promise<SDGCompliance> {
  return await apiClient.get<SDGCompliance>(
    `/tenants/${tenantId}${BASE_PATH}/sdg-compliance`
  );
}

/**
 * Get environmental impact metrics
 */
export async function getEnvironmentalImpact(
  tenantId: string,
  days: number = 30
): Promise<EnvironmentalImpact> {
  return await apiClient.get<EnvironmentalImpact>(
    `/tenants/${tenantId}${BASE_PATH}/environmental-impact?days=${days}`
  );
}

/**
 * Export grant application report
 */
export async function exportGrantReport(
  tenantId: string,
  grantType: string = 'general',
  startDate?: string,
  endDate?: string
): Promise<GrantReport> {
  const payload: any = { grant_type: grantType, format: 'json' };
  if (startDate) payload.start_date = startDate;
  if (endDate) payload.end_date = endDate;

  return await apiClient.post<GrantReport>(
    `/tenants/${tenantId}${BASE_PATH}/export/grant-report`,
    payload
  );
}
