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

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

export type ProfileMeDto = {
  id: string;
  nome: string;
  email: string;
};

export type UpdateProfilePayload = {
  nome: string;
  email: string;
};

export type ChangePasswordPayload = {
  credencialAtual: string;
  novaCredencial: string;
  confirmarNovaCredencial: string;
};

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

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

  getMe(): Observable<ProfileMeDto> {
    return this.http.get<ProfileMeDto>(`${this.baseApi}/profile/me`);
  }

  updateProfile(payload: UpdateProfilePayload): Observable<ProfileMeDto> {
    return this.http.patch<ProfileMeDto>(`${this.baseApi}/profile`, payload);
  }

  changePassword(payload: ChangePasswordPayload): Observable<void> {
    return this.http.post<void>(`${this.baseApi}/profile/change-password`, payload);
  }
}
