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

import { Company } from './company.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';

@Injectable({
  providedIn: 'root'
})
export class CompanyService implements DomainService<Company> {

  constructor(
    private apiClient: ApiClientService
  ) {}

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

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

  create(data: any): Observable<Company> {
    return this.apiClient.post<Company>('company', data);
  }

  update(id: any, data: any): Observable<Company> {
    return this.apiClient.patch<Company>(`company/${id}`, data);
  }

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

  getCompanies( 
    page = 1, 
    limit = 100, 
    filters?: {[key: string]: string}
  ): Observable<PaginatedResponse<Company>> {
    
    let url = `company?page=${page}&limit=${limit}`;
    
    if (filters) {
      const params = new URLSearchParams();
      
      for (const [key, value] of Object.entries(filters)) {
        if (value) {
          params.append(key, value);
        }
      }
      
      url += `&${params.toString()}`;
    }
    
    return this.apiClient.get<PaginatedResponse<Company>>(url);
}

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

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

 
} 