import { api } from '../index'; import { toDownloadJob, toPage, type RawDownloadJob, type RawPaged, } from '../mappers'; import type { DownloadJob, DownloadRequestResult, PaginatedResponse, } from '../types'; interface ListParams { status?: DownloadJob['status']; /** Only the current user's jobs (backend `mine=true`). */ mine?: boolean; page?: number; pageSize?: number; } interface RawCreateResponse { already_in_library: boolean; track_id: string | null; job: RawDownloadJob | null; } export const downloadsApi = api.injectEndpoints({ endpoints: (build) => ({ getDownloads: build.query< PaginatedResponse, ListParams | void >({ query: (params) => { const p = params ?? {}; const size = p.pageSize ?? 50; return { url: '/downloads', params: { status: p.status, mine: p.mine ? true : undefined, limit: size, offset: ((p.page ?? 1) - 1) * size, }, }; }, transformResponse: (raw: RawPaged) => toPage(raw, toDownloadJob), providesTags: (result) => result ? [ ...result.items.map(({ id }) => ({ type: 'Download' as const, id, })), 'Download', ] : ['Download'], }), getDownload: build.query({ query: (id) => `/downloads/${id}`, transformResponse: (raw: RawDownloadJob) => toDownloadJob(raw), providesTags: (_r, _e, id) => [{ type: 'Download', id }], }), /** Request a download of a discovered item (§A4 "Download to library"). */ createDownload: build.mutation< DownloadRequestResult, { source: string; sourceId: string; query?: string } >({ query: (body) => ({ url: '/downloads', method: 'POST', body: { source: body.source, source_id: body.sourceId, query: body.query, }, }), transformResponse: (raw: RawCreateResponse): DownloadRequestResult => ({ alreadyInLibrary: raw.already_in_library, trackId: raw.track_id ?? undefined, job: raw.job ? toDownloadJob(raw.job) : undefined, }), // A completed dedup can surface an existing library track; refresh both. invalidatesTags: ['Download', 'Track'], }), cancelDownload: build.mutation({ query: (id) => ({ url: `/downloads/${id}`, method: 'DELETE' }), invalidatesTags: ['Download'], }), retryDownload: build.mutation({ query: (id) => ({ url: `/downloads/${id}/retry`, method: 'POST' }), transformResponse: (raw: RawDownloadJob) => toDownloadJob(raw), invalidatesTags: (_r, _e, id) => [{ type: 'Download', id }, 'Download'], }), }), overrideExisting: false, }); export const { useGetDownloadsQuery, useGetDownloadQuery, useCreateDownloadMutation, useCancelDownloadMutation, useRetryDownloadMutation, } = downloadsApi;