import { api } from '@/core/services/api'
import type { CreateRolePayload, ListRolesParams, RoleListItem, RolePermission } from '../types/role.types'

type RolesApiResponse = {
  success: boolean
  data: RoleListItem[]
  message?: string
}

type RoleApiResponse = {
  success: boolean
  data: RoleListItem
  message?: string
}

type PermissionsApiResponse = {
  success: boolean
  data: RolePermission[]
  message?: string
}

export async function listRoles(params?: ListRolesParams): Promise<RolesApiResponse> {
  const { data } = await api.get<RolesApiResponse>('/v1/roles', {
    params,
  })

  if (!data.success) {
    throw new Error(data.message ?? 'Failed to load roles')
  }

  return data
}

export async function getRole(id: string): Promise<RoleApiResponse> {
  const { data } = await api.get<RoleApiResponse>(`/v1/roles/${id}`)

  if (!data.success) {
    throw new Error(data.message ?? 'Failed to load role')
  }

  return data
}

export async function createRole(payload: CreateRolePayload): Promise<RoleApiResponse> {
  const { data } = await api.post<RoleApiResponse>('/v1/roles', payload)

  if (!data.success) {
    throw new Error(data.message ?? 'Failed to create role')
  }

  return data
}

export async function updateRole(
  id: string,
  payload: CreateRolePayload,
): Promise<RoleApiResponse> {
  const { data } = await api.put<RoleApiResponse>(`/v1/roles/${id}`, payload)

  if (!data.success) {
    throw new Error(data.message ?? 'Failed to update role')
  }

  return data
}

export async function deleteRole(id: string): Promise<RoleApiResponse> {
  const { data } = await api.delete<RoleApiResponse>(`/v1/roles/${id}`)

  if (!data.success) {
    throw new Error(data.message ?? 'Failed to delete role')
  }

  return data
}

export async function listPermissions(): Promise<PermissionsApiResponse> {
  const { data } = await api.get<PermissionsApiResponse>('/v1/permissions')

  if (!data.success) {
    throw new Error(data.message ?? 'Failed to load permissions')
  }

  return data
}
