import { baseApi } from '../../base-api';
import type { PersonalDocumentSlot } from './personal-document.types';

const TAG = 'PersonalDocument' as const;
const LIST = { type: TAG, id: 'LIST' } as const;

/**
 * The applicant's own documents — identity card, photograph, education —
 * kept against their profile rather than any one application, so they survive
 * having no seafarer registration yet.
 *
 * Reads and deletes live here; the two uploads do not. `fetch` — what
 * `fetchBaseQuery` runs on — cannot report how much of a request body has gone
 * up, so they use XHR instead (`personal-document.upload.ts`) and the page
 * refetches this query when one finishes.
 */
export const personalDocumentApi = baseApi
  .enhanceEndpoints({ addTagTypes: [TAG] })
  .injectEndpoints({
    endpoints: (builder) => ({
      getMyPersonalDocuments: builder.query<{ slots: PersonalDocumentSlot[] }, void>({
        query: () => ({ url: '/profiles/me/documents' }),
        providesTags: () => [LIST],
      }),

      deletePersonalDocumentFile: builder.mutation<{ deleted: boolean }, string>({
        query: (fileId) => ({
          url: `/profiles/me/documents/files/${fileId}`,
          method: 'DELETE',
        }),
        invalidatesTags: (_r, error) => (error ? [] : [LIST]),
      }),
    }),
    overrideExisting: false,
  });

export const {
  useGetMyPersonalDocumentsQuery,
  useDeletePersonalDocumentFileMutation,
} = personalDocumentApi;
