import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from '@environments/environment';
import { Observable, map, catchError, of } from 'rxjs';

import {
  DcbTransaction,
  DcbAnalytics,
  TransactionStats,
  DcbOperator
} from '../models/dcb';

@Injectable({ providedIn: 'root' })
export class DcbService {
  private http = inject(HttpClient);
  private apiUrl = `${environment.apiUrl}/dcb`;

  // === ANALYTICS & DASHBOARD ===
  getAnalytics(timeRange: string = '7d'): Observable<DcbAnalytics> {
    return this.http.get<DcbAnalytics>(`${this.apiUrl}/analytics?range=${timeRange}`).pipe(
      catchError(error => {
        console.error('Error loading analytics:', error);
        // Retourner des données mockées en cas d'erreur
        return of(this.getMockAnalytics());
      })
    );
  }

  getTransactionStats(): Observable<TransactionStats> {
    return this.http.get<TransactionStats>(`${this.apiUrl}/analytics/stats`).pipe(
      catchError(error => {
        console.error('Error loading transaction stats:', error);
        return of({
          pending: 0,
          successful: 0,
          failed: 0,
          refunded: 0
        });
      })
    );
  }

  getRecentTransactions(limit: number = 10): Observable<DcbTransaction[]> {
    return this.http.get<DcbTransaction[]>(`${this.apiUrl}/transactions/recent?limit=${limit}`).pipe(
      catchError(error => {
        console.error('Error loading recent transactions:', error);
        return of(this.getMockTransactions());
      })
    );
  }

  getOperators(): Observable<DcbOperator[]> {
    return this.http.get<DcbOperator[]>(`${this.apiUrl}/operators`).pipe(
      catchError(error => {
        console.error('Error loading operators:', error);
        return of(this.getMockOperators());
      })
    );
  }

  // Données mockées pour le développement
  private getMockAnalytics(): DcbAnalytics {
    return {
      totalRevenue: 125430.50,
      totalTransactions: 2847,
      successRate: 87.5,
      averageAmount: 44.07,
      monthlyGrowth: 12.3,
      todayStats: {
        revenue: 3420.75,
        transactions: 78,
        successCount: 68,
        failedCount: 10
      },
      topOperators: [
        { operator: 'Orange', revenue: 45210.25, count: 1024 },
        { operator: 'Free', revenue: 38150.75, count: 865 },
        { operator: 'SFR', revenue: 22470.50, count: 512 },
        { operator: 'Bouygues', revenue: 19598.00, count: 446 }
      ],
      dailyStats: [
        { date: '2024-01-01', revenue: 3420.75, transactions: 78 },
        { date: '2024-01-02', revenue: 3985.25, transactions: 91 },
        { date: '2024-01-03', revenue: 3125.50, transactions: 71 },
        { date: '2024-01-04', revenue: 4250.00, transactions: 96 },
        { date: '2024-01-05', revenue: 3875.25, transactions: 88 },
        { date: '2024-01-06', revenue: 2980.75, transactions: 68 },
        { date: '2024-01-07', revenue: 4125.50, transactions: 94 }
      ]
    };
  }

  private getMockTransactions(): DcbTransaction[] {
    return [
      {
        id: '1',
        msisdn: '+33612345678',
        operator: 'Orange',
        country: 'FR',
        amount: 4.99,
        currency: 'EUR',
        status: 'SUCCESS',
        productName: 'Premium Content',
        transactionDate: new Date('2024-01-07T14:30:00'),
        createdAt: new Date('2024-01-07T14:30:00')
      },
      {
        id: '2',
        msisdn: '+33798765432',
        operator: 'Free',
        country: 'FR',
        amount: 2.99,
        currency: 'EUR',
        status: 'PENDING',
        productName: 'Basic Subscription',
        transactionDate: new Date('2024-01-07T14:25:00'),
        createdAt: new Date('2024-01-07T14:25:00')
      },
      {
        id: '3', 
        msisdn: '+33687654321',
        operator: 'SFR',
        country: 'FR',
        amount: 9.99,
        currency: 'EUR',
        status: 'FAILED',
        productName: 'Pro Package',
        transactionDate: new Date('2024-01-07T14:20:00'),
        createdAt: new Date('2024-01-07T14:20:00'),
        errorCode: 'INSUFFICIENT_FUNDS',
        errorMessage: 'Solde insuffisant'
      }
    ];
  }

  private getMockOperators(): DcbOperator[] {
    return [
      { id: '1', name: 'Orange', code: 'ORANGE', country: 'FR', status: 'ACTIVE', successRate: 92.5 },
      { id: '2', name: 'Free', code: 'FREE', country: 'FR', status: 'ACTIVE', successRate: 88.2 },
      { id: '3', name: 'SFR', code: 'SFR', country: 'FR', status: 'ACTIVE', successRate: 85.7 },
      { id: '4', name: 'Bouygues', code: 'BOUYGTEL', country: 'FR', status: 'ACTIVE', successRate: 83.9 }
    ];
  }
}