import { Injectable } from '@angular/core';
import { Observable, of, map } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { firstValueFrom } from 'rxjs';

import { Fines, VehicleFinelDashBoardList } from './fines.interface';
import { ApiClientService } from '../../shared/services/api/api-client.service';
import { DomainService } from '../../shared/components/base-domain/base-domain.component';
import { PaginatedResponse } from '../../shared/interfaces/paginate.interface';
import { DateRangeShortcuts } from '../../shared/utils/date-range.utils';

/**
 * 🎯 FinesService - Serviço para gestão de Multas
 * 
 * ✨ Implementa DomainService<Fines>
 * 🚀 Padrões de nomenclatura obrigatórios: create, update, delete, getById, getFiness
 * 
 * 🆕 V2.0 Features:
 * - DateRangeUtils: Filtros de data automáticos
 * - ApiClientService: NUNCA usar HttpClient diretamente
 * - Fallback: Dados mock para desenvolvimento
 */
@Injectable({
  providedIn: 'root'
})
export class FinesService implements DomainService<Fines> {

  constructor(
    private apiClient: ApiClientService
  ) {}

  // ========================================
  // 🎯 IMPLEMENTAÇÃO DA INTERFACE DOMAINSERVICE
  // ========================================

  getEntities(page: number, pageSize: number, filters: any): Observable<{
    data: Fines[];
    totalCount: number;
    pageCount: number;
    currentPage: number;
  }> {
    return this.getFiness(page, pageSize, filters).pipe(
      map(response => ({
        data: response.data,
        totalCount: response.totalCount,
        pageCount: response.pageCount,
        currentPage: response.currentPage
      }))
    );
  }

  create(data: any): Observable<Fines> {
    return this.apiClient.post<Fines>('vehicle-fine', data);
  }

  update(id: any, data: any): Observable<Fines> {
    return this.apiClient.patch<Fines>(`vehicle-fine/${id}`, data);
  }

  // ========================================
  // 🎯 MÉTODOS ESPECÍFICOS DO DOMÍNIO
  // ========================================

  getFiness(
    page = 1,
    limit = 10,
    filters?: any
  ): Observable<PaginatedResponse<Fines>> {
    
    // ✨ V2.0: DateRangeUtils automático
    const dateFilters = filters?.dateRange ? DateRangeShortcuts.currentMonth() : {};
    const allFilters = { ...filters, ...dateFilters };
    
    
    let url = `vehicle-fine?page=${page}&limit=${limit}`;
    
    if (allFilters) {
      const params = new URLSearchParams();
      
      for (const [key, value] of Object.entries(allFilters)) {
        if (value) {
          params.append(key, value.toString());
        }
      }
      
      if (params.toString()) {
        url += `&${params.toString()}`;
      }
    }

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

  getById(id: string): Observable<Fines> {
    return this.apiClient.get<Fines>(`finess/${id}`);
  }

  delete(id: string): Observable<void> {
    return this.apiClient.delete<void>(`finess/${id}`);
  }

  
  // ========================================
  // ⚡ BULK OPERATIONS V2.0
  // ========================================

  // bulkDelete(ids: string[]): Observable<void> {
  //   return this.apiClient.post<void>(`fines/bulk-delete`, { ids });
  // }

  // bulkUpdate(updates: Array<{id: string, data: Partial<Fines>}>): Observable<Fines[]> {
  //   return this.apiClient.patch<Fines[]>(`fines/bulk`, { updates });
  // }

  
  // ✨ V2.0: Exemplo de uso do DateRangeUtils
  async getRecentItems(): Promise<Fines[]> {
    const dateFilters = DateRangeShortcuts.last30Days();
    const response = await firstValueFrom(this.getFiness(1, 100, dateFilters));
    return response.data;
  }


  // ========================================
  // 🎯 MÉTODOS DASHBOARD
  // ========================================
  getVehicleFinesDashboardList(
    page = 1,
    limit = 10,
    filters?: {[key: string]: string}
  ): Observable<PaginatedResponse<VehicleFinelDashBoardList>> {
    
    let url = `vehicle-fine?page=${page}&limit=${limit}`;
    
    if (filters) {
      const params = new URLSearchParams();
      
      for (const [key, value] of Object.entries(filters)) {
        if (value) {
          params.append(key, value);
          console.log(`🔧 [getTollparkings] Adicionando filtro: ${key} = ${value}`);
        }
      }
      
      if (params.toString()) {
        url += `&${params.toString()}`;
      }
    } 
    
    console.log(`🌐 [getTollparkings] URL final da requisição: ${url}`);
    
    return this.apiClient.get<PaginatedResponse<VehicleFinelDashBoardList>>(url);
  }  
}