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 { FinancialCategory } from './financial-category.interface';
import { PaginatedResponse } from '../../../shared/interfaces/paginate.interface';
import { DomainService } from '../../../shared/components/base-domain/base-domain.component';

@Injectable({
    providedIn: 'root' 
})
export class FinancialCategoriesService implements DomainService<FinancialCategory> { 
    constructor(
        private apiClient: ApiClientService,
        private papa: Papa
    ) {}

    /**
     * Busca categorias financeiras com paginação e filtros
     */
    getFinancialCategories( 
        page = 1, 
        limit = 10, 
        filters?: {[key: string]: string}
    ): Observable<PaginatedResponse<FinancialCategory>> {
        
        let url = `FinancialCategory?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<FinancialCategory>>(url);
    }

    /**
     * Busca uma categoria financeira específica por ID
     */
    getById(id: string | number): Observable<FinancialCategory> {
        return this.apiClient.get<FinancialCategory>(`fFinancialCategory/${id}`);
    }
    
    /**
     * ✅ Método genérico para criar - chamado automaticamente pelo BaseDomainComponent
     */
    create(data: any): Observable<FinancialCategory> {
        return this.apiClient.post<FinancialCategory>('FinancialCategory', data);
    }

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

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

    /**
     * Busca subcategorias de uma categoria pai
     */
    getSubcategories(parentId: string | number): Observable<FinancialCategory[]> {
        return this.apiClient.get<FinancialCategory[]>(`FinancialCategory/${parentId}/subcategories`);
    }

    /**
     * Busca categorias por tipo (income, expense, etc.)
     */
    getCategoriesByType(type: string): Observable<FinancialCategory[]> {
        return this.apiClient.get<FinancialCategory[]>(`FinancialCategory/type/${type}`);
    }

    // ========================================
    // 🎯 MÉTODOS ESPERADOS PELO BaseDomainComponent
    // ========================================
    
    /**
     * ✅ Método genérico para listar - chamado automaticamente pelo BaseDomainComponent
     */
    getEntities(page: number, pageSize: number, filters: any): Observable<{
        data: FinancialCategory[];
        totalCount: number;
        pageCount: number;
        currentPage: number;
    }> {
        return this.getFinancialCategories(page, pageSize, filters).pipe(
            map(response => ({
                data: response.data,
                totalCount: response.totalCount,
                pageCount: response.pageCount,
                currentPage: response.currentPage
            }))
        );
    }


} 