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 {
  UserDto, UserListItemDto, CreateUserRequest, CreateUserResult,
  UpdateUserRequest, UserQueryParams, PagedResult
} from '../models/user.model';

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

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

  getPaged(params: UserQueryParams = {}): Observable<PagedResult<UserListItemDto>> {
    let p = new HttpParams()
      .set('page',     params.page     ?? 1)
      .set('pageSize', params.pageSize ?? 20);
    if (params.search) p = p.set('search', params.search);
    return this.http.get<PagedResult<UserListItemDto>>(this.endpoint, { params: p });
  }

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

  createUser(request: CreateUserRequest): Observable<CreateUserResult> {
    return this.http.post<CreateUserResult>(this.endpoint, request);
  }

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

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

  resetPassword(id: string): Observable<{ tempPassword: string }> {
    return this.http.post<{ tempPassword: string }>(
      `${this.endpoint}/${id}/reset-password`, {});
  }
}
