import type { Project, ProjectWrite } from './dto/project'
import type { HydraCollection } from '~/utils/api'
import { extractHydraMembers } from '~/utils/api'

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

    async function getAll(params?: { archived?: boolean }): Promise<Project[]> {
        const query = params?.archived !== undefined ? `?archived=${params.archived}` : ''
        const data = await api.get<HydraCollection<Project>>(`/projects${query}`)
        return extractHydraMembers(data)
    }

    async function getById(id: number): Promise<Project> {
        return api.get<Project>(`/projects/${id}`)
    }

    async function create(payload: ProjectWrite): Promise<Project> {
        return api.post<Project>('/projects', payload as Record<string, unknown>, {
            toastSuccessKey: 'projects.created',
        })
    }

    async function update(id: number, payload: Partial<ProjectWrite>, options?: { toastSuccessKey?: string }): Promise<Project> {
        return api.patch<Project>(`/projects/${id}`, payload as Record<string, unknown>, {
            toastSuccessKey: options?.toastSuccessKey ?? 'projects.updated',
        })
    }

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

    return { getAll, getById, create, update, remove }
}
