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

/**
 * The officer's own signing signature — drawn onto certificates they approve
 * (`{{signatureImage}}`), as distinct from the seafarer's specimen signature
 * that the portal manages.
 *
 * Scoped to the caller: the API resolves the employee record from the token,
 * so no employee id is passed and nobody can upload on another's behalf.
 */
const signatureApi = baseApi
  .enhanceEndpoints({ addTagTypes: ['MyEmployeeSignature'] as const })
  .injectEndpoints({
    endpoints: (builder) => ({
      getMyEmployeeSignature: builder.query<{ url: string | null }, void>({
        query: () => ({ url: '/employee-signatures/me' }),
        providesTags: ['MyEmployeeSignature'],
      }),

      uploadMyEmployeeSignature: builder.mutation<{ id: string }, File>({
        query: (file) => {
          const body = new FormData();
          body.append('file', file);
          // No Content-Type header: fetch sets it with the multipart boundary.
          return { url: '/employee-signatures/me', method: 'POST', body };
        },
        invalidatesTags: (_r, error) => (error ? [] : ['MyEmployeeSignature']),
      }),

      deleteMyEmployeeSignature: builder.mutation<{ removed: boolean }, void>({
        query: () => ({ url: '/employee-signatures/me', method: 'DELETE' }),
        invalidatesTags: (_r, error) => (error ? [] : ['MyEmployeeSignature']),
      }),
    }),
    overrideExisting: false,
  });

export const {
  useGetMyEmployeeSignatureQuery,
  useUploadMyEmployeeSignatureMutation,
  useDeleteMyEmployeeSignatureMutation,
} = signatureApi;
