import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { GroupOfUser } from '../../models/user-management.api.models';
import { ApiService } from './user-management.api.service';
import { Observable, firstValueFrom } from 'rxjs';
import { UrlService } from './url.service';

@Injectable({
  providedIn: 'root'
})
export class GroupOfUserService extends ApiService<GroupOfUser> {
  constructor(http: HttpClient, urlService: UrlService) {
    super(http, urlService.apiRoute.groupOfUser);
  }

  deleteByGroupUserId(groupId: number, userId: number): Observable<any> {
    const url = `${this.baseUrl}?groupId=${groupId}&userId=${userId}`;
    return this.http.delete<any>(url, { withCredentials: true });
  }

  override getAll(withUser: boolean = false, withGroup: boolean = false): Observable<GroupOfUser[]> {
    let params = new HttpParams();
    if (withUser) {
      params = params.set('withUser', withUser);
    }
    if (withGroup) {
      params = params.set('withGroup', withGroup);
    }

    return this.http.get<GroupOfUser[]>(this.baseUrl, { params, withCredentials: true });
  }

  async getByUsername(username: string): Promise<GroupOfUser[]> {
    const url = `${this.baseUrl}?username=${username}`;
    return await firstValueFrom(this.http.get<GroupOfUser[]>(url, { withCredentials: true }));
  }
}