import { baseApi } from '../../base-api';
import type {
  CreateMedicalCertificate,
  CreateSeaServiceRecord,
  MedicalCertificate,
  RecordQueueFilter,
  SeaServiceRecord,
  SeaTimeSummary,
  SeafarerStatus,
} from './seafarer.types';

const TAGS = ['SeaServiceRecord', 'MedicalCertificate'] as const;

const listTag = (type: (typeof TAGS)[number]) => ({ type, id: 'LIST' }) as const;

/**
 * The seafarer's evidence shelf: sea-service records and medical
 * certificates (modules 05/06). Registration itself lives in
 * `seafarer-registration-api.ts`.
 */
export const seafarerApi = baseApi
  .enhanceEndpoints({ addTagTypes: TAGS })
  .injectEndpoints({
    endpoints: (builder) => ({
      // ---------------------------------------------------------- sea service
      getMySeaServiceRecords: builder.query<SeaServiceRecord[], void>({
        query: () => ({ url: '/sea-service-records/mine' }),
        providesTags: () => [listTag('SeaServiceRecord')],
      }),

      getSeaServiceForProfile: builder.query<SeaServiceRecord[], string>({
        query: (profileId) => ({
          url: `/sea-service-records/profile/${profileId}`,
        }),
        providesTags: () => [listTag('SeaServiceRecord')],
      }),

      createSeaServiceRecord: builder.mutation<
        SeaServiceRecord,
        CreateSeaServiceRecord
      >({
        query: (body) => ({ url: '/sea-service-records', method: 'POST', body }),
        invalidatesTags: (_r, error) =>
          error ? [] : [listTag('SeaServiceRecord')],
      }),

      updateSeaServiceRecord: builder.mutation<
        SeaServiceRecord,
        { id: string; body: Partial<CreateSeaServiceRecord> }
      >({
        query: ({ id, body }) => ({
          url: `/sea-service-records/${id}`,
          method: 'PUT',
          body,
        }),
        invalidatesTags: (_r, error) =>
          error ? [] : [listTag('SeaServiceRecord')],
      }),

      deleteSeaServiceRecord: builder.mutation<unknown, string>({
        query: (id) => ({ url: `/sea-service-records/${id}`, method: 'DELETE' }),
        invalidatesTags: (_r, error) =>
          error ? [] : [listTag('SeaServiceRecord')],
      }),

      // -------------------------------------------------------------- medical
      getMyMedicalCertificates: builder.query<MedicalCertificate[], void>({
        query: () => ({ url: '/medical-certificates/mine' }),
        providesTags: () => [listTag('MedicalCertificate')],
      }),

      getMedicalForProfile: builder.query<MedicalCertificate[], string>({
        query: (profileId) => ({
          url: `/medical-certificates/profile/${profileId}`,
        }),
        providesTags: () => [listTag('MedicalCertificate')],
      }),

      createMedicalCertificate: builder.mutation<
        MedicalCertificate,
        CreateMedicalCertificate
      >({
        query: (body) => ({ url: '/medical-certificates', method: 'POST', body }),
        invalidatesTags: (_r, error) =>
          error ? [] : [listTag('MedicalCertificate')],
      }),

      updateMedicalCertificate: builder.mutation<
        MedicalCertificate,
        { id: string; body: Partial<CreateMedicalCertificate> }
      >({
        query: ({ id, body }) => ({
          url: `/medical-certificates/${id}`,
          method: 'PUT',
          body,
        }),
        invalidatesTags: (_r, error) =>
          error ? [] : [listTag('MedicalCertificate')],
      }),

      deleteMedicalCertificate: builder.mutation<unknown, string>({
        query: (id) => ({ url: `/medical-certificates/${id}`, method: 'DELETE' }),
        invalidatesTags: (_r, error) =>
          error ? [] : [listTag('MedicalCertificate')],
      }),

      // -------------------------------------------------------- verification
      getPendingSeaService: builder.query<
        SeaServiceRecord[],
        RecordQueueFilter | void
      >({
        query: (status) => ({
          url: '/sea-service-records/pending',
          params: { status: status || 'SUBMITTED' },
        }),
        providesTags: () => [listTag('SeaServiceRecord')],
      }),

      getPendingMedical: builder.query<
        MedicalCertificate[],
        RecordQueueFilter | void
      >({
        query: (status) => ({
          url: '/medical-certificates/pending',
          params: { status: status || 'SUBMITTED' },
        }),
        providesTags: () => [listTag('MedicalCertificate')],
      }),

      verifySeaServiceRecord: builder.mutation<
        SeaServiceRecord,
        { id: string; outcome: 'VERIFIED' | 'REJECTED'; remark?: string }
      >({
        query: ({ id, ...body }) => ({
          url: `/sea-service-records/${id}/verify`,
          method: 'POST',
          body,
        }),
        invalidatesTags: (_r, error) =>
          error ? [] : [listTag('SeaServiceRecord')],
      }),

      verifyMedicalCertificate: builder.mutation<
        MedicalCertificate,
        { id: string; outcome: 'VERIFIED' | 'REJECTED'; remark?: string }
      >({
        query: ({ id, ...body }) => ({
          url: `/medical-certificates/${id}/verify`,
          method: 'POST',
          body,
        }),
        invalidatesTags: (_r, error) =>
          error ? [] : [listTag('MedicalCertificate')],
      }),

      getMySeaTime: builder.query<SeaTimeSummary, void>({
        query: () => ({ url: '/sea-service-records/mine/sea-time' }),
        providesTags: () => [listTag('SeaServiceRecord')],
      }),

      getSeaTimeForProfile: builder.query<SeaTimeSummary, string>({
        query: (profileId) => ({
          url: `/sea-service-records/profile/${profileId}/sea-time`,
        }),
        providesTags: () => [listTag('SeaServiceRecord')],
      }),

      // ----------------------------------------------- registry (backoffice)
      /** US-SEA-013: suspend, reinstate or close with a mandatory reason. */
      updateSeafarerStatus: builder.mutation<
        unknown,
        { profileId: string; status: SeafarerStatus; reason: string }
      >({
        query: ({ profileId, ...body }) => ({
          url: `/profiles/${profileId}/seafarer-status`,
          method: 'POST',
          body,
        }),
      }),
    }),
  });

export const {
  useGetPendingSeaServiceQuery,
  useGetPendingMedicalQuery,
  useVerifySeaServiceRecordMutation,
  useVerifyMedicalCertificateMutation,
  useGetMySeaTimeQuery,
  useGetSeaTimeForProfileQuery,
  useGetMySeaServiceRecordsQuery,
  useGetSeaServiceForProfileQuery,
  useCreateSeaServiceRecordMutation,
  useUpdateSeaServiceRecordMutation,
  useDeleteSeaServiceRecordMutation,
  useGetMyMedicalCertificatesQuery,
  useGetMedicalForProfileQuery,
  useCreateMedicalCertificateMutation,
  useUpdateMedicalCertificateMutation,
  useDeleteMedicalCertificateMutation,
  useUpdateSeafarerStatusMutation,
} = seafarerApi;
