import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';

import { environment } from '../../environments/environment';

export type UserPermission = 'sysadmin' | 'gestor' | 'cliente';

export type UserDto = {
  id: string;
  nome: string;
  email: string;
  permissao: UserPermission;
  tenantId: string;
  ativo?: boolean;
};

export type ApiFieldError = {
  field?: string | null;
  message: string;
};

export type ApiErrorResponse = {
  errors?: ApiFieldError[];
};

export type CreateUserPayload = {
  nome: string;
  email: string;
  senha: string;
  confirmarSenha: string;
  permissao: UserPermission;
};

export type UsersListParams = {
  search?: string;
  permissao?: UserPermission;
  page?: number;
  pageSize?: number;
};

export type UpdateUserPayload = {
  nome?: string;
  email?: string;
  senha?: string;
  confirmarSenha?: string;
  permissao?: UserPermission;
  ativo?: boolean;
};

export type PagedResult<T> = {
  items: T[];
  total: number;
  page: number;
  pageSize: number;
};

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

  constructor(private http: HttpClient) {
    const raw = (environment.apiUrl || '').replace(/\/+$/, '');
    this.baseApi = raw.toLowerCase().endsWith('/api') ? raw : `${raw}/api`;
  }

  create(payload: CreateUserPayload): Observable<UserDto> {
    return this.http.post<UserDto>(`${this.baseApi}/users`, payload);
  }

  list(params: UsersListParams): Observable<PagedResult<UserDto>> {
    let httpParams = new HttpParams();
    if (params.search) httpParams = httpParams.set('search', params.search);
    if (params.permissao) httpParams = httpParams.set('permissao', params.permissao);
    if (params.page) httpParams = httpParams.set('page', String(params.page));
    if (params.pageSize) httpParams = httpParams.set('pageSize', String(params.pageSize));
    return this.http.get<PagedResult<UserDto>>(`${this.baseApi}/users`, { params: httpParams });
  }

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

  update(id: string, payload: UpdateUserPayload): Observable<void> {
    return this.http.patch<void>(`${this.baseApi}/users/${id}`, payload);
  }

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