import { Injectable } from '@angular/core';
import { Observable, map } from 'rxjs';
import { Papa } from 'ngx-papaparse';
import { ApiClientService } from '../../shared/services/api/api-client.service';
import { Company } from './company.interface';
import { PaginatedResponse } from '../../shared/interfaces/paginate.interface';
import { DomainService } from '../../shared/components/base-domain/base-domain.component';

/**
 * 🏢 CompaniesService - Gerenciamento de Empresas
 * 
 * Integração com API PraFrota Backend seguindo padrão estabelecido.
 * 
 * Endpoints:
 * - GET    /company       - Listar empresas
 * - POST   /company       - Criar empresa
 * - PATCH  /company/:id   - Atualizar empresa
 * - DELETE /company/:id   - Deletar empresa
 * - GET    /company/:id   - Buscar empresa por ID
 */
@Injectable({
    providedIn: 'root' 
})
export class CompaniesService implements DomainService<Company> { 
    constructor(
        private apiClient: ApiClientService,
        private papa: Papa
    ) {}

    getCompanies( 
        page = 1, 
        limit = 10, 
        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);
    }

    /**
     * Busca uma empresa específica por ID
     */
    getById(id: string | number): Observable<Company> {
        return this.apiClient.get<Company>(`company/${id}`);
    }

    /**
     * Remove uma empresa
     */
    delete(id: string | number): Observable<void> {
        return this.apiClient.delete<void>(`company/${id}`);
    }

    // ========================================
    // 🎯 MÉTODOS ESPERADOS PELO BaseDomainComponent
    // ========================================
    /**
     * ✅ Método genérico para listar - chamado automaticamente pelo BaseDomainComponent
     */
    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
            }))
        );
    }

    /**
     * ✅ Método genérico para criar - chamado automaticamente pelo BaseDomainComponent
     */
    create(data: any): Observable<Company> {
        return this.apiClient.post<Company>('company', data);
    }

    /**
     * ✅ Método genérico para atualizar - chamado automaticamente pelo BaseDomainComponent
     */
    update(id: any, data: any): Observable<Company> {
        return this.apiClient.patch<Company>(`company/${id}`, data);
    }

    // 🔍 MÉTODOS ESPECÍFICOS PARA EMPRESAS

    /**
     * Buscar empresa por CNPJ
     */
    getByCnpj(cnpj: string): Observable<Company[]> {
        return this.apiClient.get<Company[]>(`company?cnpj=${cnpj}`);
    }

    /**
     * Buscar empresas por tipo
     */
    getByType(type: string): Observable<Company[]> {
        return this.apiClient.get<Company[]>(`company?company_type=${type}`);
    }

    /**
     * Buscar empresas ativas
     */
    getActiveCompanies(): Observable<Company[]> {
        return this.apiClient.get<Company[]>(`company?active=true`);
    }

    /**
     * Buscar empresas por segmento
     */
    getBySegment(segment: string): Observable<Company[]> {
        return this.apiClient.get<Company[]>(`company?segment=${segment}`);
    }
} 