import api from './axios-instance';
import { API_ENDPOINTS } from '@constants/api-endpoints';
import type { User } from '@shared/types/entities.types';
import type { ApiResponse, PaginatedResponse, PaginationParams } from '@shared/types/api.types';

export interface CreateUserDto {
  email: string;
  password: string;
  firstName: string;
  lastName: string;
  roles?: string[];
}

export interface UpdateUserDto {
  email?: string;
  firstName?: string;
  lastName?: string;
  isActive?: boolean;
}

export const usersApi = {
  getAll: async (params?: PaginationParams): Promise<PaginatedResponse<User>> => {
    const response = await api.get<PaginatedResponse<User>>(
      API_ENDPOINTS.USERS.BASE,
      { params }
    );
    return response.data;
  },

  getById: async (id: string): Promise<User> => {
    const response = await api.get<ApiResponse<User>>(
      API_ENDPOINTS.USERS.BY_ID(id)
    );
    if (!response.data.success || !response.data.data) {
      throw new Error(response.data.error || 'Usuario no encontrado');
    }
    return response.data.data;
  },

  create: async (data: CreateUserDto): Promise<User> => {
    const response = await api.post<ApiResponse<User>>(
      API_ENDPOINTS.USERS.BASE,
      data
    );
    if (!response.data.success || !response.data.data) {
      throw new Error(response.data.error || 'Error al crear usuario');
    }
    return response.data.data;
  },

  update: async (id: string, data: UpdateUserDto): Promise<User> => {
    const response = await api.put<ApiResponse<User>>(
      API_ENDPOINTS.USERS.BY_ID(id),
      data
    );
    if (!response.data.success || !response.data.data) {
      throw new Error(response.data.error || 'Error al actualizar usuario');
    }
    return response.data.data;
  },

  delete: async (id: string): Promise<void> => {
    const response = await api.delete<ApiResponse>(
      API_ENDPOINTS.USERS.BY_ID(id)
    );
    if (!response.data.success) {
      throw new Error(response.data.error || 'Error al eliminar usuario');
    }
  },

  updateRoles: async (id: string, roles: string[]): Promise<User> => {
    const response = await api.put<ApiResponse<User>>(
      API_ENDPOINTS.USERS.ROLES(id),
      { roles }
    );
    if (!response.data.success || !response.data.data) {
      throw new Error(response.data.error || 'Error al actualizar roles');
    }
    return response.data.data;
  },

  changePassword: async (
    id: string,
    currentPassword: string,
    newPassword: string
  ): Promise<void> => {
    const response = await api.post<ApiResponse>(
      API_ENDPOINTS.USERS.CHANGE_PASSWORD(id),
      { currentPassword, newPassword }
    );
    if (!response.data.success) {
      throw new Error(response.data.error || 'Error al cambiar contraseña');
    }
  },
};
