import type {
    BookStackSettings,
    BookStackSettingsWrite,
    BookStackTestResult,
    BookStackShelf,
    BookStackLink,
    BookStackLinkCreate,
    BookStackSearchResult,
} from './dto/bookstack'
import type { HydraCollection } from '~/utils/api'
import { extractHydraMembers } from '~/utils/api'

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

    async function getSettings(): Promise<BookStackSettings> {
        return api.get<BookStackSettings>('/settings/bookstack')
    }

    async function saveSettings(payload: BookStackSettingsWrite): Promise<BookStackSettings> {
        return api.put<BookStackSettings>('/settings/bookstack', payload as Record<string, unknown>, {
            toastSuccessKey: 'bookstack.settings.saved',
        })
    }

    async function testConnection(): Promise<BookStackTestResult> {
        return api.post<BookStackTestResult>('/settings/bookstack/test')
    }

    async function listShelves(): Promise<BookStackShelf[]> {
        const data = await api.get<HydraCollection<BookStackShelf>>('/bookstack/shelves')
        return extractHydraMembers(data)
    }

    async function getLinks(taskId: number): Promise<BookStackLink[]> {
        const data = await api.get<HydraCollection<BookStackLink>>(`/tasks/${taskId}/bookstack/links`)
        return extractHydraMembers(data)
    }

    async function addLink(taskId: number, payload: BookStackLinkCreate): Promise<BookStackLink> {
        return api.post<BookStackLink>(`/tasks/${taskId}/bookstack/links`, payload as Record<string, unknown>)
    }

    async function removeLink(taskId: number, linkId: number): Promise<void> {
        await api.delete(`/tasks/${taskId}/bookstack/links/${linkId}`)
    }

    async function search(taskId: number, query: string): Promise<BookStackSearchResult[]> {
        const data = await api.get<HydraCollection<BookStackSearchResult>>(
            `/tasks/${taskId}/bookstack/search`,
            { q: query },
        )
        return extractHydraMembers(data)
    }

    return {
        getSettings,
        saveSettings,
        testConnection,
        listShelves,
        getLinks,
        addLink,
        removeLink,
        search,
    }
}
