import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable } from 'rxjs';
import { environment } from '../../../environments/environment';
import {
  AdminPlayerFilters,
  AdminPlayerPage,
  AdminUserDirectorySummary,
  AdminUserProfileRequest,
  AdminUserRoleRequest,
  AdminUserStatusRequest,
} from '../../models/user-directory.model';

@Injectable({ providedIn: 'root' })
export class AdminUsersApi {
  private readonly http = inject(HttpClient);
  private readonly baseUrl = `${environment.apiUrl}admin/users`;

  updateProfile(userId: number, request: AdminUserProfileRequest): Observable<AdminUserDirectorySummary> {
    return this.http.patch<AdminUserDirectorySummary>(`${this.baseUrl}/${userId}/profile`, request);
  }

  updateRole(userId: number, request: AdminUserRoleRequest): Observable<AdminUserDirectorySummary> {
    return this.http.patch<AdminUserDirectorySummary>(`${this.baseUrl}/${userId}/role`, request);
  }

  updateStatus(userId: number, request: AdminUserStatusRequest): Observable<AdminUserDirectorySummary> {
    return this.http.patch<AdminUserDirectorySummary>(`${this.baseUrl}/${userId}/status`, request);
  }

  loadPlayers(filters: AdminPlayerFilters = {}): Observable<AdminPlayerPage> {
    return this.http.get<AdminPlayerPage>(`${this.baseUrl}/players`, { params: this.toParams(filters) });
  }

  assignPlayer(userId: number, playerId: number): Observable<AdminUserDirectorySummary> {
    return this.http.put<AdminUserDirectorySummary>(`${this.baseUrl}/${userId}/players/${playerId}`, null);
  }

  unlinkPlayer(userId: number, playerId: number): Observable<AdminUserDirectorySummary> {
    return this.http.delete<AdminUserDirectorySummary>(`${this.baseUrl}/${userId}/players/${playerId}`);
  }

  private toParams(filters: AdminPlayerFilters): HttpParams {
    let params = new HttpParams();
    if (filters.search !== undefined) params = params.set('search', filters.search);
    if (filters.teamId !== undefined) params = params.set('teamId', filters.teamId);
    if (filters.assignment !== undefined) params = params.set('assignment', filters.assignment);
    if (filters.page !== undefined) params = params.set('page', filters.page);
    if (filters.limit !== undefined) params = params.set('limit', filters.limit);
    return params;
  }
}
