import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Transaction } from '../../model';
import { environment } from 'src/environments/environment';
import { TeamInvite } from './model/team-invite';

@Injectable({
  providedIn: 'root'
})
export class TeamsService {

  team: any;
  selectedUserTransaction: any[];
  transactionsLoading: boolean = false;

  constructor(private http: HttpClient) {
    this.selectedUserTransaction = [];
  }

  loadTransactionsOfUser(userId: number) {
    this.transactionsLoading = true;
    const url = `${environment.apiUrl}teams/${this.team.id}/${userId}`;
    this.http.get(url).subscribe(res => {
      this.selectedUserTransaction = res as any;
      this.transactionsLoading = false;
    })
  }

  loadTeamDetails(id: string): Observable<any> {
    return this.http.get(`${environment.apiUrl}teams/${id}`);
  }

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

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

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

  createNewPlayer(teamId: number, player: {firstName: string, lastName: string, teamRole: number}) {
    return this.http.post(`${environment.apiUrl}teams/${teamId}/players`, player);
  }

  createRegisterLink(invite: TeamInvite): Observable<any> {
    return this.http.post(`${environment.apiUrl}auth/invite`, invite);
  }

  validateRegistrationToken(token: string): Observable<any> {
    return this.http.post(`${environment.apiUrl}auth/verify-invite`, { token });
  }

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