import { baseApi } from '@ema-platform/api';

/**
 * The caller's specimen signature.
 *
 * Upload is multipart rather than the presign+PUT flow used for documents:
 * the API validates type and size on the way through, which it cannot do when
 * bytes go straight to storage. `signatureUrl` on the profile is an
 * object-storage key, so the stored signature is displayed through a
 * short-lived link from `GET me/signature` rather than read off the profile.
 */
const signatureApi = baseApi
  .enhanceEndpoints({ addTagTypes: ['CurrentProfile', 'MySignature'] as const })
  .injectEndpoints({
    endpoints: (builder) => ({
      getMySignature: builder.query<{ url: string | null }, void>({
        query: () => ({ url: '/profiles/me/signature' }),
        providesTags: ['MySignature'],
      }),

      uploadMySignature: builder.mutation<{ signatureUrl: string }, File>({
        query: (file) => {
          const body = new FormData();
          body.append('file', file);
          // No Content-Type header: fetch sets it with the multipart boundary,
          // and naming it here would omit the boundary and fail to parse.
          return { url: '/profiles/me/signature', method: 'POST', body };
        },
        invalidatesTags: (_r, error) =>
          error ? [] : ['MySignature', 'CurrentProfile'],
      }),

      deleteMySignature: builder.mutation<{ signatureUrl: null }, void>({
        query: () => ({ url: '/profiles/me/signature', method: 'DELETE' }),
        invalidatesTags: (_r, error) =>
          error ? [] : ['MySignature', 'CurrentProfile'],
      }),
    }),
    overrideExisting: false,
  });

export const {
  useGetMySignatureQuery,
  useUploadMySignatureMutation,
  useDeleteMySignatureMutation,
} = signatureApi;
