import type { Workflow, WorkflowWrite } from './dto/workflow'
import type { HydraCollection } from '~/utils/api'
import { extractHydraMembers } from '~/utils/api'

type SwitchPayload = {
    workflowId: number
    mapping: Record<string, number | null>
}

type SwitchResult = {
    projectId: number
    workflowId: number
    migratedTaskCount: number
}

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

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

    async function getOne(id: number): Promise<Workflow> {
        return api.get<Workflow>(`/workflows/${id}`)
    }

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

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

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

    async function switchOnProject(projectId: number, payload: SwitchPayload): Promise<SwitchResult> {
        return api.post<SwitchResult>(
            `/projects/${projectId}/switch-workflow`,
            payload as unknown as Record<string, unknown>,
            { toastSuccessKey: 'workflows.switched' },
        )
    }

    return { getAll, getOne, create, update, remove, switchOnProject }
}
