import { api } from '@services/api/axios-instance';
import type {
  User,
  Role,
  CreateUserDto,
  UpdateUserDto,
  UserFilters,
  UsersResponse,
} from '../types';

const BASE_URL = '/api/v1/users';

export const usersApi = {
  // Get all users with filters
  getAll: async (filters?: UserFilters): Promise<UsersResponse> => {
    const params = new URLSearchParams();
    if (filters?.search) params.append('search', filters.search);
    if (filters?.status) params.append('status', filters.status);
    if (filters?.roleId) params.append('roleId', filters.roleId);
    if (filters?.page) params.append('page', String(filters.page));
    if (filters?.limit) params.append('limit', String(filters.limit));
    if (filters?.sortBy) params.append('sortBy', filters.sortBy);
    if (filters?.sortOrder) params.append('sortOrder', filters.sortOrder);

    const response = await api.get<UsersResponse>(`${BASE_URL}?${params.toString()}`);
    return response.data;
  },

  // Get user by ID
  getById: async (id: string): Promise<User> => {
    const response = await api.get<User>(`${BASE_URL}/${id}`);
    return response.data;
  },

  // Create user
  create: async (data: CreateUserDto): Promise<User> => {
    const response = await api.post<User>(BASE_URL, data);
    return response.data;
  },

  // Update user
  update: async (id: string, data: UpdateUserDto): Promise<User> => {
    const response = await api.patch<User>(`${BASE_URL}/${id}`, data);
    return response.data;
  },

  // Delete user
  delete: async (id: string): Promise<void> => {
    await api.delete(`${BASE_URL}/${id}`);
  },

  // Activate user
  activate: async (id: string): Promise<User> => {
    const response = await api.post<User>(`${BASE_URL}/${id}/activate`);
    return response.data;
  },

  // Deactivate user
  deactivate: async (id: string): Promise<User> => {
    const response = await api.post<User>(`${BASE_URL}/${id}/deactivate`);
    return response.data;
  },

  // Reset password
  resetPassword: async (id: string): Promise<void> => {
    await api.post(`${BASE_URL}/${id}/reset-password`);
  },
};

// Roles API
export const rolesApi = {
  getAll: async (): Promise<Role[]> => {
    const response = await api.get<Role[]>('/api/v1/roles');
    return response.data;
  },

  getById: async (id: string): Promise<Role> => {
    const response = await api.get<Role>(`/api/v1/roles/${id}`);
    return response.data;
  },
};
