/**
 * Serviço de Perfis
 */

import { apiClient } from "../api/client";
import type {
  Profile,
  UpdateProfileAvatarInput,
  ProfileFilters,
} from "./types";

class ProfileService {
  private readonly basePath = "/profiles";

  /**
   * Lista perfis de usuários com filtros opcionais
   */
  async list(filters?: ProfileFilters): Promise<Profile[]> {
    const params: Record<string, string> = {};

    if (filters?.full_name) {
      params["full_name"] = `ilike.*${filters.full_name}*`;
    }

    if (filters?.email) {
      params["email"] = `ilike.*${filters.email}*`;
    }

    if (filters?.phone) {
      params["phone"] = `eq.${filters.phone}`;
    }

    if (filters?.disabled !== undefined) {
      params["disabled"] = `eq.${filters.disabled}`;
    }

    const response = await apiClient.get<Profile[]>(this.basePath, { params });
    return response.data;
  }

  /**
   * Busca perfil por ID
   */
  async getById(id: string): Promise<Profile> {
    const response = await apiClient.get<Profile>(`${this.basePath}/${id}`);
    return response.data;
  }

  /**
   * Atualiza avatar_url no perfil
   */
  async updateAvatar(
    userId: string,
    data: UpdateProfileAvatarInput
  ): Promise<Profile> {
    const response = await apiClient.patch<Profile>(
      `${this.basePath}/${userId}`,
      data
    );
    return response.data;
  }
}

export const profileService = new ProfileService();
