import { Injectable, inject, signal } from '@angular/core';
import { take } from 'rxjs/operators';
import { AdminTransaction, AdminTransactionListFilters } from '../models/admin-transaction.model';
import { ADMIN_TRANSACTIONS_GATEWAY } from '../services/admin-transactions-gateway.token';

@Injectable({ providedIn: 'root' })
export class AdminTransactionsFacade {
  private readonly gateway = inject(ADMIN_TRANSACTIONS_GATEWAY);

  readonly filters = signal<AdminTransactionListFilters>({ search: '', status: 'all', type: 'all', page: 1, pageSize: 10 });
  readonly transactions = signal<AdminTransaction[]>([]);
  readonly total = signal(0);
  readonly loading = signal(false);
  readonly error = signal<string | null>(null);

  loadList(): void {
    this.loading.set(true);
    this.error.set(null);
    this.gateway.loadTransactions(this.filters()).pipe(take(1)).subscribe({
      next: result => {
        this.transactions.set(result.items);
        this.total.set(result.total);
        this.loading.set(false);
      },
      error: () => {
        this.transactions.set([]);
        this.total.set(0);
        this.loading.set(false);
        this.error.set('common.errorDescription');
      }
    });
  }

  updateFilters(patch: Partial<AdminTransactionListFilters>): void {
    this.filters.update(current => ({ ...current, ...patch, page: patch.page ?? 1 }));
    this.loadList();
  }

  retryFailed(id: string): void {
    this.gateway.retryFailed(id).pipe(take(1)).subscribe({ next: () => this.loadList() });
  }

  toggleFraudFlag(id: string, flagged: boolean): void {
    this.gateway.setFraudFlag(id, flagged).pipe(take(1)).subscribe({ next: () => this.loadList() });
  }

  exportCsv(): string {
    const header = 'Order Number,Type,Method,Status,Amount,Currency,Fraud Flag,Created At';
    const rows = this.transactions().map(tx =>
      [tx.orderNumber, tx.type, tx.method, tx.status, tx.amount, tx.currency, tx.fraudFlag, tx.createdAt].join(',')
    );
    return [header, ...rows].join('\n');
  }
}
