/**
 * Food Safety Service - Mirror backend food safety endpoints
 */
import { apiClient } from '../client';
import {
  FoodSafetyComplianceCreate,
  FoodSafetyComplianceUpdate,
  FoodSafetyComplianceResponse,
  TemperatureLogCreate,
  BulkTemperatureLogCreate,
  TemperatureLogResponse,
  FoodSafetyAlertCreate,
  FoodSafetyAlertUpdate,
  FoodSafetyAlertResponse,
  FoodSafetyFilter,
  TemperatureMonitoringFilter,
  FoodSafetyMetrics,
  TemperatureAnalytics,
  FoodSafetyDashboard,
} from '../types/foodSafety';
import { PaginatedResponse } from '../types/inventory';

export class FoodSafetyService {
  private readonly baseUrl = '/tenants';

  // Compliance Management
  async createComplianceRecord(
    tenantId: string,
    complianceData: FoodSafetyComplianceCreate
  ): Promise<FoodSafetyComplianceResponse> {
    return apiClient.post<FoodSafetyComplianceResponse>(
      `${this.baseUrl}/${tenantId}/food-safety/compliance`,
      complianceData
    );
  }

  async getComplianceRecord(
    tenantId: string,
    recordId: string
  ): Promise<FoodSafetyComplianceResponse> {
    return apiClient.get<FoodSafetyComplianceResponse>(
      `${this.baseUrl}/${tenantId}/food-safety/compliance/${recordId}`
    );
  }

  async getComplianceRecords(
    tenantId: string,
    filter?: FoodSafetyFilter
  ): Promise<PaginatedResponse<FoodSafetyComplianceResponse>> {
    const queryParams = new URLSearchParams();
    
    if (filter?.compliance_type) queryParams.append('compliance_type', filter.compliance_type);
    if (filter?.status) queryParams.append('status', filter.status);
    if (filter?.ingredient_id) queryParams.append('ingredient_id', filter.ingredient_id);
    if (filter?.resolved !== undefined) queryParams.append('resolved', filter.resolved.toString());
    if (filter?.date_range?.start) queryParams.append('start_date', filter.date_range.start);
    if (filter?.date_range?.end) queryParams.append('end_date', filter.date_range.end);
    if (filter?.limit !== undefined) queryParams.append('limit', filter.limit.toString());
    if (filter?.offset !== undefined) queryParams.append('offset', filter.offset.toString());
    if (filter?.order_by) queryParams.append('order_by', filter.order_by);
    if (filter?.order_direction) queryParams.append('order_direction', filter.order_direction);

    const url = queryParams.toString() 
      ? `${this.baseUrl}/${tenantId}/food-safety/compliance?${queryParams.toString()}`
      : `${this.baseUrl}/${tenantId}/food-safety/compliance`;

    return apiClient.get<PaginatedResponse<FoodSafetyComplianceResponse>>(url);
  }

  async updateComplianceRecord(
    tenantId: string,
    recordId: string,
    updateData: FoodSafetyComplianceUpdate
  ): Promise<FoodSafetyComplianceResponse> {
    return apiClient.put<FoodSafetyComplianceResponse>(
      `${this.baseUrl}/${tenantId}/food-safety/compliance/${recordId}`,
      updateData
    );
  }

  async deleteComplianceRecord(
    tenantId: string,
    recordId: string
  ): Promise<{ message: string }> {
    return apiClient.delete<{ message: string }>(
      `${this.baseUrl}/${tenantId}/food-safety/compliance/${recordId}`
    );
  }

  // Temperature Monitoring
  async createTemperatureLog(
    tenantId: string,
    logData: TemperatureLogCreate
  ): Promise<TemperatureLogResponse> {
    return apiClient.post<TemperatureLogResponse>(
      `${this.baseUrl}/${tenantId}/food-safety/temperature-logs`,
      logData
    );
  }

  async createBulkTemperatureLogs(
    tenantId: string,
    bulkData: BulkTemperatureLogCreate
  ): Promise<{
    created_count: number;
    failed_count: number;
    errors?: string[];
  }> {
    return apiClient.post(
      `${this.baseUrl}/${tenantId}/food-safety/temperature-logs/bulk`,
      bulkData
    );
  }

  async getTemperatureLogs(
    tenantId: string,
    filter?: TemperatureMonitoringFilter
  ): Promise<PaginatedResponse<TemperatureLogResponse>> {
    const queryParams = new URLSearchParams();
    
    if (filter?.location) queryParams.append('location', filter.location);
    if (filter?.equipment_id) queryParams.append('equipment_id', filter.equipment_id);
    if (filter?.temperature_range?.min !== undefined) 
      queryParams.append('min_temperature', filter.temperature_range.min.toString());
    if (filter?.temperature_range?.max !== undefined) 
      queryParams.append('max_temperature', filter.temperature_range.max.toString());
    if (filter?.alert_triggered !== undefined) 
      queryParams.append('alert_triggered', filter.alert_triggered.toString());
    if (filter?.date_range?.start) queryParams.append('start_date', filter.date_range.start);
    if (filter?.date_range?.end) queryParams.append('end_date', filter.date_range.end);
    if (filter?.limit !== undefined) queryParams.append('limit', filter.limit.toString());
    if (filter?.offset !== undefined) queryParams.append('offset', filter.offset.toString());
    if (filter?.order_by) queryParams.append('order_by', filter.order_by);
    if (filter?.order_direction) queryParams.append('order_direction', filter.order_direction);

    const url = queryParams.toString() 
      ? `${this.baseUrl}/${tenantId}/food-safety/temperature-logs?${queryParams.toString()}`
      : `${this.baseUrl}/${tenantId}/food-safety/temperature-logs`;

    return apiClient.get<PaginatedResponse<TemperatureLogResponse>>(url);
  }

  async getTemperatureAnalytics(
    tenantId: string,
    location: string,
    startDate?: string,
    endDate?: string
  ): Promise<TemperatureAnalytics> {
    const queryParams = new URLSearchParams();
    queryParams.append('location', location);
    if (startDate) queryParams.append('start_date', startDate);
    if (endDate) queryParams.append('end_date', endDate);

    return apiClient.get<TemperatureAnalytics>(
      `${this.baseUrl}/${tenantId}/food-safety/temperature-analytics?${queryParams.toString()}`
    );
  }

  // Alert Management
  async createFoodSafetyAlert(
    tenantId: string,
    alertData: FoodSafetyAlertCreate
  ): Promise<FoodSafetyAlertResponse> {
    return apiClient.post<FoodSafetyAlertResponse>(
      `${this.baseUrl}/${tenantId}/food-safety/alerts`,
      alertData
    );
  }

  async getFoodSafetyAlert(
    tenantId: string,
    alertId: string
  ): Promise<FoodSafetyAlertResponse> {
    return apiClient.get<FoodSafetyAlertResponse>(
      `${this.baseUrl}/${tenantId}/food-safety/alerts/${alertId}`
    );
  }

  async getFoodSafetyAlerts(
    tenantId: string,
    status?: 'open' | 'in_progress' | 'resolved' | 'dismissed',
    severity?: 'critical' | 'warning' | 'info',
    limit: number = 50,
    offset: number = 0
  ): Promise<PaginatedResponse<FoodSafetyAlertResponse>> {
    const queryParams = new URLSearchParams();
    if (status) queryParams.append('status', status);
    if (severity) queryParams.append('severity', severity);
    queryParams.append('limit', limit.toString());
    queryParams.append('offset', offset.toString());

    return apiClient.get<PaginatedResponse<FoodSafetyAlertResponse>>(
      `${this.baseUrl}/${tenantId}/food-safety/alerts?${queryParams.toString()}`
    );
  }

  async updateFoodSafetyAlert(
    tenantId: string,
    alertId: string,
    updateData: FoodSafetyAlertUpdate
  ): Promise<FoodSafetyAlertResponse> {
    return apiClient.put<FoodSafetyAlertResponse>(
      `${this.baseUrl}/${tenantId}/food-safety/alerts/${alertId}`,
      updateData
    );
  }

  async deleteFoodSafetyAlert(
    tenantId: string,
    alertId: string
  ): Promise<{ message: string }> {
    return apiClient.delete<{ message: string }>(
      `${this.baseUrl}/${tenantId}/food-safety/alerts/${alertId}`
    );
  }

  // Dashboard and Metrics
  async getFoodSafetyDashboard(tenantId: string): Promise<FoodSafetyDashboard> {
    return apiClient.get<FoodSafetyDashboard>(
      `${this.baseUrl}/${tenantId}/food-safety/dashboard`
    );
  }

  async getFoodSafetyMetrics(
    tenantId: string,
    startDate?: string,
    endDate?: string
  ): Promise<FoodSafetyMetrics> {
    const queryParams = new URLSearchParams();
    if (startDate) queryParams.append('start_date', startDate);
    if (endDate) queryParams.append('end_date', endDate);

    const url = queryParams.toString() 
      ? `${this.baseUrl}/${tenantId}/food-safety/metrics?${queryParams.toString()}`
      : `${this.baseUrl}/${tenantId}/food-safety/metrics`;

    return apiClient.get<FoodSafetyMetrics>(url);
  }

  async getTemperatureViolations(
    tenantId: string,
    limit: number = 20
  ): Promise<TemperatureLogResponse[]> {
    const queryParams = new URLSearchParams();
    queryParams.append('limit', limit.toString());

    return apiClient.get<TemperatureLogResponse[]>(
      `${this.baseUrl}/${tenantId}/food-safety/temperature-violations?${queryParams.toString()}`
    );
  }

  async getComplianceRate(
    tenantId: string,
    startDate?: string,
    endDate?: string
  ): Promise<{
    overall_rate: number;
    by_type: Record<string, number>;
    trend: Array<{ date: string; rate: number }>;
  }> {
    const queryParams = new URLSearchParams();
    if (startDate) queryParams.append('start_date', startDate);
    if (endDate) queryParams.append('end_date', endDate);

    const url = queryParams.toString() 
      ? `${this.baseUrl}/${tenantId}/food-safety/compliance-rate?${queryParams.toString()}`
      : `${this.baseUrl}/${tenantId}/food-safety/compliance-rate`;

    return apiClient.get(url);
  }
}

export const foodSafetyService = new FoodSafetyService();