// Role CRUD + permission assignment (ERPCore Controllers/RolesController.cs).
import { apiRequest, apiRequestWithETag, buildQuery } from "@/lib/api-client"
import { ApiResult, EntityStatus, PagedResponse } from "@/types/common"
import {
  AssignRolePermissionsRequest,
  CreateRoleRequest,
  Role,
  RolePermissions,
  UpdateRoleRequest,
} from "@/types/rbac"

export interface ListRolesParams {
  page?: number
  pageSize?: number
  q?: string
  status?: EntityStatus
}

export const rolesApi = {
  list(params: ListRolesParams = {}): Promise<PagedResponse<Role>> {
    return apiRequest<PagedResponse<Role>>(`/roles${buildQuery(params)}`)
  },

  get(roleId: number): Promise<ApiResult<Role>> {
    return apiRequestWithETag<Role>(`/roles/${roleId}`)
  },

  create(request: CreateRoleRequest): Promise<ApiResult<Role>> {
    return apiRequestWithETag<Role>("/roles", { method: "POST", body: request })
  },

  update(roleId: number, request: UpdateRoleRequest, ifMatch: string): Promise<ApiResult<Role>> {
    return apiRequestWithETag<Role>(`/roles/${roleId}`, { method: "PUT", body: request, ifMatch })
  },

  updateStatus(roleId: number, status: EntityStatus): Promise<void> {
    return apiRequest<void>(`/roles/${roleId}/status`, { method: "PATCH", body: { status } })
  },

  remove(roleId: number): Promise<void> {
    return apiRequest<void>(`/roles/${roleId}`, { method: "DELETE" })
  },

  getPermissions(roleId: number): Promise<RolePermissions> {
    return apiRequest<RolePermissions>(`/roles/${roleId}/permissions`)
  },

  assignPermissions(roleId: number, request: AssignRolePermissionsRequest): Promise<RolePermissions> {
    return apiRequest<RolePermissions>(`/roles/${roleId}/permissions`, { method: "PUT", body: request })
  },
}
