import type { Permission } from './permissions'
import type { HydraCollection } from '~/utils/api'
import { extractHydraMembers } from '~/utils/api'

export type Role = {
    id: number
    '@id'?: string
    code: string
    label: string
    description?: string | null
    isSystem: boolean
    permissions: Permission[]
}

export type RoleWrite = {
    code?: string
    label: string
    description?: string | null
    /** IRIs of the granted permissions (e.g. /api/permissions/3). */
    permissions: string[]
}

export function useRoleService() {
    const api = useApi()

    async function list(): Promise<Role[]> {
        const data = await api.get<HydraCollection<Role>>('/roles')
        return extractHydraMembers(data)
    }

    async function create(payload: RoleWrite): Promise<Role> {
        return api.post<Role>('/roles', payload as Record<string, unknown>, {
            toastSuccessKey: 'admin.roles.created',
        })
    }

    async function update(id: number, payload: Partial<RoleWrite>): Promise<Role> {
        return api.patch<Role>(`/roles/${id}`, payload as Record<string, unknown>, {
            toastSuccessKey: 'admin.roles.updated',
        })
    }

    async function remove(id: number): Promise<void> {
        await api.delete(`/roles/${id}`, {}, {
            toastSuccessKey: 'admin.roles.deleted',
        })
    }

    return { list, create, update, remove }
}
