import { HttpClient } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable } from 'rxjs';
import { environment } from '../../../environments/environment';
import { Team } from '../../models/team.model';
import { PlayerTransaction } from '../../models/transaction.model';
import { UserTeamMembership } from '../../models/user-directory.model';
import { Player } from '../../models/player.model';

export interface CreatePlayerRequest {
  firstName: string;
  lastName: string;
  teamRole: number;
}

export interface CreateTeamRequest {
  name: string;
}

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

  loadMyTeams(userId: number): Observable<UserTeamMembership[]> {
    return this.http.get<UserTeamMembership[]>(`${environment.apiUrl}users/${userId}/teams`);
  }

  loadTeamOverview(teamId: number): Observable<Team> {
    return this.http.get<Team>(`${environment.apiUrl}teams/${teamId}/overview`);
  }

  createTeam(request: CreateTeamRequest): Observable<Team> {
    return this.http.post<Team>(`${environment.apiUrl}teams`, request);
  }

  createPlayer(teamId: number, player: CreatePlayerRequest): Observable<Player> {
    return this.http.post<Player>(`${environment.apiUrl}teams/${teamId}/players`, player);
  }

  updatePlayer(teamId: number, player: Player): Observable<Player> {
    return this.http.put<Player>(`${environment.apiUrl}teams/${teamId}/players`, player);
  }

  setPlayerActive(teamId: number, playerId: number, active: boolean): Observable<Player> {
    return this.http.patch<Player>(
      `${environment.apiUrl}teams/${teamId}/players/${playerId}/active`,
      { active },
    );
  }

  setPlayerTeamRole(teamId: number, playerId: number, teamRoleId: number): Observable<Player> {
    return this.http.patch<Player>(
      `${environment.apiUrl}teams/${teamId}/players/${playerId}/team-role`,
      { teamRoleId },
    );
  }

  loadPlayerTransactions(teamId: number, playerId: number): Observable<PlayerTransaction[]> {
    return this.http.get<PlayerTransaction[]>(
      `${environment.apiUrl}teams/${teamId}/players/${playerId}/transactions`,
    );
  }
}
