/**
 * Users resource: CRUD, lock/unlock, roles, password
 */

import type { AxiosInstance } from 'axios';
import { API_PATHS } from '@effigenix/config';
import type {
  UserDTO,
  RoleDTO,
  CreateUserRequest,
  UpdateUserRequest,
  ChangePasswordRequest,
  AssignRoleRequest,
} from '@effigenix/types';

export type {
  UserDTO,
  RoleDTO,
  CreateUserRequest,
  UpdateUserRequest,
  ChangePasswordRequest,
  AssignRoleRequest,
};

export function createUsersResource(client: AxiosInstance) {
  return {
    async list(): Promise<UserDTO[]> {
      const response = await client.get<UserDTO[]>(API_PATHS.users.base);
      return response.data;
    },

    async getById(id: string): Promise<UserDTO> {
      const response = await client.get<UserDTO>(API_PATHS.users.byId(id));
      return response.data;
    },

    async create(request: CreateUserRequest): Promise<UserDTO> {
      const response = await client.post<UserDTO>(API_PATHS.users.base, request);
      return response.data;
    },

    async update(id: string, request: UpdateUserRequest): Promise<UserDTO> {
      const response = await client.put<UserDTO>(API_PATHS.users.byId(id), request);
      return response.data;
    },

    async lock(id: string): Promise<UserDTO> {
      const response = await client.post<UserDTO>(API_PATHS.users.lock(id));
      return response.data;
    },

    async unlock(id: string): Promise<UserDTO> {
      const response = await client.post<UserDTO>(API_PATHS.users.unlock(id));
      return response.data;
    },

    async assignRole(id: string, request: AssignRoleRequest): Promise<UserDTO> {
      const response = await client.post<UserDTO>(API_PATHS.users.roles(id), request);
      return response.data;
    },

    async removeRole(id: string, roleName: string): Promise<void> {
      await client.delete(`${API_PATHS.users.roles(id)}/${encodeURIComponent(roleName)}`);
    },

    async changePassword(id: string, request: ChangePasswordRequest): Promise<void> {
      await client.put(API_PATHS.users.password(id), request);
    },
  };
}

export type UsersResource = ReturnType<typeof createUsersResource>;
