import { Injectable } from '@angular/core';
import { Observable, map, tap } from 'rxjs';
import { ApiClientService } from '../../../../shared/services/api/api-client.service';
import { AccountPayable, AccountPayableItem, AccountPayableItemResponse } from '../interfaces/accountpayable.interface';
import { DomainService } from '../../../../shared/components/base-domain/base-domain.component';
import { PaginatedResponse } from '../../../../shared/interfaces/paginate.interface';
import { Attachments } from '../../../../shared/interfaces/attachments';

@Injectable({
    providedIn: 'root'
  })
  export class AccountPayableService implements DomainService<AccountPayable> {
    constructor(
      private apiClient: ApiClientService,
    ) {}

    getEntities(page: number, pageSize: number, filters: any): Observable<{
      data: AccountPayable[];
      totalCount: number;
      pageCount: number;
      currentPage: number;
    }> {
      return this.getAccountPayables(page, pageSize, filters).pipe(
        map(response => ({
          data: response.data,
          totalCount: response.totalCount,
          pageCount: response.pageCount,
          currentPage: response.currentPage
        }))
      );
    } 
    getAccountPayables(
      page = 1, 
      limit = 10, 
      filters?: {[key: string]: string}
    ): Observable<PaginatedResponse<AccountPayable>> {
      
      let url = `account-payable?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<AccountPayable>>(url);
    }
    getById(id: string): Observable<AccountPayable> {
      return this.apiClient.get<AccountPayable>(`account-payable/${id}`);
    }
    create(data: any): Observable<AccountPayable> {
      return this.apiClient.post<AccountPayable>('account-payable', data);
    }
    update(id: any, data: any): Observable<AccountPayable> {
      return this.apiClient.patch<AccountPayable>(`account-payable/${id}`, data);
    }
    delete(id: string): Observable<void> {
      return this.apiClient.delete<void>(`account-payable/${id}`);
    }

    getAttachmentsById(id: string): Observable<{ data: Attachments[] }> {
      return this.apiClient.get<{ data: Attachments[] }>(`account-payable/${id}/attachments`);
    }

    // // ========================================
    // // 🎯 MÉTODOS PARA GERENCIAMENTO DE ITENS
    // // ========================================
    getAccountPayableItems(accountPayableId: number | string): Observable<AccountPayableItem[]> {
      const url = `account-payable/${accountPayableId}?page=1&limit=100`;
      
      return this.apiClient.get<AccountPayableItemResponse>(url).pipe(
          map(response => response.data?.accountPayableItem || []),
          tap(items => console.log(`✅ Loaded ${items.length} items for account payable ${accountPayableId}`))
      );
    }

    // ========================================
    // 🎯 MÉTODOS PARA DASHBOARD
    // ========================================
    getAccountPayablesDashboard(
      page = 1, 
      limit = 10, 
      filters?: {[key: string]: string}
    ): Observable<PaginatedResponse<AccountPayable>> {
      
      let url = `account-payable/dashboard/list?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<AccountPayable>>(url);
    }
    

    // createAccountPayableItem(accountPayableId: string, data: any): Observable<AccountPayableItem> {
    //   return this.apiClient.post<AccountPayableItem>(`account-payable/${accountPayableId}/items`, data);
    // }

    // updateAccountPayableItem(accountPayableId: string, itemId: string, data: any): Observable<AccountPayableItem> {
    //   return this.apiClient.patch<AccountPayableItem>(`account-payable/${accountPayableId}/items/${itemId}`, data);
    // }

    // deleteAccountPayableItem(accountPayableId: string, itemId: string): Observable<void> {
    //   return this.apiClient.delete<void>(`account-payable/${accountPayableId}/items/${itemId}`);
    // }

    // ========================================
    // 🎯 MÉTODOS PARA PROCESSAMENTO DE PAGAMENTOS
    // ========================================

    // markItemAsPaid(accountPayableId: string, itemId: string, paymentData: any): Observable<AccountPayableItem> {
    //   return this.apiClient.patch<AccountPayableItem>(`account-payable/${accountPayableId}/items/${itemId}/pay`, paymentData);
    // }

    // markItemAsCancelled(accountPayableId: string, itemId: string, reason?: string): Observable<AccountPayableItem> {
    //   return this.apiClient.patch<AccountPayableItem>(`account-payable/${accountPayableId}/items/${itemId}/cancel`, { reason });
    // }
    // approveAccountPayable(id: string, data?: any): Observable<AccountPayable> {
    //   return this.apiClient.patch<AccountPayable>(`account-payable/${id}/approve`, data);
    // }

    // refuseAccountPayable(id: string, reason: string): Observable<AccountPayable> {
    //   return this.apiClient.patch<AccountPayable>(`account-payable/${id}/refuse`, { reason });
    // }

    // ========================================
    // 🎯 MÉTODOS PARA RELATÓRIOS E TOTALIZAÇÕES
    // ========================================

    // getAccountPayableSummary(accountPayableId: string): Observable<{
    //   totalValue: number;
    //   totalPaid: number;
    //   totalPending: number;
    //   totalCancelled: number;
    //   itemCount: number;
    // }> {
    //   return this.apiClient.get<any>(`account-payable/${accountPayableId}/summary`);
    // }
    // ========================================
    // 🎯 MÉTODOS LEGADOS (MANTER COMPATIBILIDADE)
    // ========================================
    // /** @deprecated Use getAccountPayables instead */
    // getAccountPayable(
    //     page = 1, 
    //     limit = 10, 
    //     filters?: {[key: string]: string}
    //   ): Observable<PaginatedResponse<AccountPayable>> {
    //     console.warn('getAccountPayable is deprecated, use getAccountPayables instead');
    //     return this.getAccountPayables(page, limit, filters);
    // }
}