import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable } from 'rxjs';
import { environment } from '../../../environments/environment';
import {
  CreatePlayerTransaction,
  CreateTeamWalletTransaction,
  TeamActivity,
  TransactionsJournalPage,
  TransactionsJournalQuery,
} from '../../models/transaction.model';

@Injectable({ providedIn: 'root' })
export class TransactionsApi {
  private readonly http = inject(HttpClient);

  loadTeamTransactions(teamId: number): Observable<TeamActivity[]> {
    return this.http.get<TeamActivity[]>(`${environment.apiUrl}teams/${teamId}/transactions`);
  }

  loadTeamTransactionsJournal(
    teamId: number,
    query: TransactionsJournalQuery,
  ): Observable<TransactionsJournalPage> {
    let params = new HttpParams()
      .set('page', query.page)
      .set('limit', query.limit)
      .set('sortBy', query.sortBy)
      .set('sortDir', query.sortDir);
    if (query.search) params = params.set('search', query.search);
    if (query.type) params = params.set('type', query.type);

    return this.http.get<TransactionsJournalPage>(
      `${environment.apiUrl}teams/${teamId}/transactions/journal`,
      { params },
    );
  }

  createPlayerTransactions(transactions: CreatePlayerTransaction[]): Observable<TeamActivity[]> {
    return this.http.post<TeamActivity[]>(`${environment.apiUrl}transactions`, transactions);
  }

  createTeamWalletTransaction(transaction: CreateTeamWalletTransaction): Observable<TeamActivity> {
    return this.http.post<TeamActivity>(
      `${environment.apiUrl}team-wallet-transactions`,
      transaction,
    );
  }

  reverseTransaction(transactionId: number): Observable<TeamActivity> {
    return this.http.post<TeamActivity>(
      `${environment.apiUrl}transactions/${transactionId}/reverse`,
      {},
    );
  }
}
