import { baseApi } from '../../base-api';
import type { ApplicationPayment, InitiatePaymentResult } from '../licensing/licensing.types';
import type {
  SeafarerDocument,
  SeafarerDocumentDetail,
  SeafarerDocumentKind,
  SeafarerDocumentRequestKind,
  SeafarerDocumentRow,
  SeafarerDocumentStatus,
} from './seafarer-document.types';

const TAG = 'SeafarerDocument' as const;
const LIST = { type: TAG, id: 'LIST' } as const;
const item = (id: string) => ({ type: TAG, id }) as const;

export interface SeafarerDocumentListFilter {
  kind?: SeafarerDocumentKind;
  requestKind?: SeafarerDocumentRequestKind;
  status?: SeafarerDocumentStatus;
  search?: string;
  take?: number;
  skip?: number;
}

/**
 * Seaman Book and BTC — own endpoints, not licence applications. Fees settle
 * through the same payment gateway, under `/seafarer-documents/:id/payments`.
 */
export const seafarerDocumentApi = baseApi
  .enhanceEndpoints({ addTagTypes: [TAG] })
  .injectEndpoints({
    endpoints: (builder) => ({
      // ------------------------------------------------------------ applicant
      getMySeafarerDocuments: builder.query<
        { seamanBook: SeafarerDocument | null; btc: SeafarerDocument | null },
        void
      >({
        query: () => ({ url: '/seafarer-documents/mine' }),
        providesTags: () => [LIST],
      }),

      getMySeafarerDocumentDownload: builder.query<{ url: string }, string>({
        query: (id) => ({ url: `/seafarer-documents/${id}/download` }),
      }),

      initiateDocumentPayment: builder.mutation<
        InitiatePaymentResult,
        { id: string; provider?: string; platform?: 'web' | 'mobile'; payerAccount?: string }
      >({
        query: ({ id, ...body }) => ({
          url: `/seafarer-documents/${id}/payments/initiate`,
          method: 'POST',
          body,
        }),
        invalidatesTags: (_r, error, { id }) => (error ? [] : [LIST, item(id)]),
      }),

      getDocumentPayment: builder.query<ApplicationPayment, string>({
        query: (id) => ({ url: `/seafarer-documents/${id}/payments` }),
        providesTags: (_r, _e, id) => [item(id)],
      }),

      bypassDocumentPayment: builder.mutation<{ status: SeafarerDocumentStatus }, string>({
        query: (id) => ({ url: `/seafarer-documents/${id}/payments/bypass`, method: 'POST' }),
        invalidatesTags: (_r, error, id) => (error ? [] : [LIST, item(id)]),
      }),

      renewSeafarerDocument: builder.mutation<SeafarerDocument, string>({
        query: (id) => ({ url: `/seafarer-documents/${id}/renew`, method: 'POST' }),
        invalidatesTags: (_r, error) => (error ? [] : [LIST]),
      }),

      replaceSeafarerDocument: builder.mutation<SeafarerDocument, string>({
        query: (id) => ({ url: `/seafarer-documents/${id}/replace`, method: 'POST' }),
        invalidatesTags: (_r, error) => (error ? [] : [LIST]),
      }),

      // --------------------------------------------------------------- review
      listSeafarerDocuments: builder.query<
        { total: number; items: SeafarerDocumentRow[] },
        SeafarerDocumentListFilter
      >({
        query: (params) => ({ url: '/seafarer-document-review', params }),
        providesTags: () => [LIST],
      }),

      getSeafarerDocumentReview: builder.query<SeafarerDocumentDetail, string>({
        query: (id) => ({ url: `/seafarer-document-review/${id}` }),
        providesTags: (_r, _e, id) => [item(id)],
      }),

      getSeafarerDocumentReviewDownload: builder.query<{ url: string }, string>({
        query: (id) => ({ url: `/seafarer-document-review/${id}/download` }),
      }),

      confirmSeafarerDocumentPayment: builder.mutation<SeafarerDocument, string>({
        query: (id) => ({ url: `/seafarer-document-review/${id}/confirm-payment`, method: 'POST' }),
        invalidatesTags: (_r, error, id) => (error ? [] : [LIST, item(id)]),
      }),

      scheduleSeafarerDocument: builder.mutation<
        SeafarerDocument,
        { id: string; scheduledDate: string }
      >({
        query: ({ id, ...body }) => ({
          url: `/seafarer-document-review/${id}/schedule-issuance`,
          method: 'POST',
          body,
        }),
        invalidatesTags: (_r, error, { id }) => (error ? [] : [LIST, item(id)]),
      }),

      issueSeafarerDocument: builder.mutation<SeafarerDocument, string>({
        query: (id) => ({ url: `/seafarer-document-review/${id}/issue`, method: 'POST' }),
        invalidatesTags: (_r, error, id) => (error ? [] : [LIST, item(id)]),
      }),

      rejectSeafarerDocument: builder.mutation<SeafarerDocument, { id: string; reason: string }>({
        query: ({ id, ...body }) => ({
          url: `/seafarer-document-review/${id}/reject`,
          method: 'POST',
          body,
        }),
        invalidatesTags: (_r, error, { id }) => (error ? [] : [LIST, item(id)]),
      }),
    }),
    overrideExisting: false,
  });

export const {
  useGetMySeafarerDocumentsQuery,
  useLazyGetMySeafarerDocumentDownloadQuery,
  useInitiateDocumentPaymentMutation,
  useGetDocumentPaymentQuery,
  useBypassDocumentPaymentMutation,
  useRenewSeafarerDocumentMutation,
  useReplaceSeafarerDocumentMutation,
  useListSeafarerDocumentsQuery,
  useGetSeafarerDocumentReviewQuery,
  useLazyGetSeafarerDocumentReviewDownloadQuery,
  useConfirmSeafarerDocumentPaymentMutation,
  useScheduleSeafarerDocumentMutation,
  useIssueSeafarerDocumentMutation,
  useRejectSeafarerDocumentMutation,
} = seafarerDocumentApi;
