import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
import { ApiConfigService } from '../../../core/services/api-config.service';
import {
  MemberDto, MemberListItemDto, CreateMemberRequest,
  UpdateMemberRequest, MemberQueryParams, PagedResult
} from '../models/member.model';

@Injectable({ providedIn: 'root' })
export class MemberApiService {
  private readonly endpoint: string;

  constructor(private http: HttpClient, apiConfig: ApiConfigService) {
    this.endpoint = apiConfig.getApiUrl('members');
  }

  getPaged(params: MemberQueryParams = {}): Observable<PagedResult<MemberListItemDto>> {
    let p = new HttpParams()
      .set('page',     params.page     ?? 1)
      .set('pageSize', params.pageSize ?? 20);
    if (params.search   !== undefined && params.search   !== '') p = p.set('search',  params.search);
    if (params.status   !== undefined && params.status   !== '') p = p.set('status',  params.status);
    if (params.hasUser  !== undefined)                           p = p.set('hasUser', params.hasUser);
    return this.http.get<PagedResult<MemberListItemDto>>(this.endpoint, { params: p });
  }

  getById(id: number): Observable<MemberDto> {
    return this.http.get<MemberDto>(`${this.endpoint}/${id}`);
  }

  create(request: CreateMemberRequest): Observable<{ id: number }> {
    return this.http.post<{ id: number }>(this.endpoint, request);
  }

  update(id: number, request: UpdateMemberRequest): Observable<void> {
    return this.http.put<void>(`${this.endpoint}/${id}`, request);
  }

  delete(id: number): Observable<void> {
    return this.http.delete<void>(`${this.endpoint}/${id}`);
  }
}
