import { baseApi } from '../../base-api';
import type { Attachment } from '../licensing/licensing.types';
import type {
  SaveSeafarerRegistration,
  SeafarerRegistration,
  SeafarerRegistrationStatus,
} from './seafarer-registration.types';

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

export type SeafarerRegistrationSortField =
  | 'submittedAt'
  | 'registrationNumber'
  | 'lastName'
  | 'status';

export interface SeafarerRegistrationListFilter {
  status?: SeafarerRegistrationStatus;
  search?: string;
  sortBy?: SeafarerRegistrationSortField;
  sortDir?: 'ASC' | 'DESC';
  take?: number;
  skip?: number;
}

/**
 * Seafarer registration — its own endpoints, not a licence application.
 * Uploads still go through `/attachments` with ownerType SEAFARER_REGISTRATION.
 */
export const seafarerRegistrationApi = baseApi
  .enhanceEndpoints({ addTagTypes: [TAG] })
  .injectEndpoints({
    endpoints: (builder) => ({
      // ------------------------------------------------------------ applicant
      getMySeafarerRegistration: builder.query<{ registration: SeafarerRegistration | null }, void>({
        query: () => ({ url: '/seafarer-registrations/mine' }),
        providesTags: (r) => [LIST, ...(r?.registration ? [item(r.registration.id)] : [])],
      }),

      startSeafarerRegistration: builder.mutation<SeafarerRegistration, void>({
        query: () => ({ url: '/seafarer-registrations', method: 'POST' }),
        invalidatesTags: (_r, error) => (error ? [] : [LIST]),
      }),

      cancelSeafarerRegistration: builder.mutation<void, string>({
        query: (id) => ({ url: `/seafarer-registrations/${id}`, method: 'DELETE' }),
        invalidatesTags: (_r, error, id) => (error ? [] : [LIST, item(id)]),
      }),

      saveSeafarerRegistration: builder.mutation<
        SeafarerRegistration,
        { id: string; body: SaveSeafarerRegistration }
      >({
        query: ({ id, body }) => ({ url: `/seafarer-registrations/${id}`, method: 'PUT', body }),
        invalidatesTags: (_r, error, { id }) => (error ? [] : [LIST, item(id)]),
      }),

      submitSeafarerRegistration: builder.mutation<SeafarerRegistration, string>({
        query: (id) => ({ url: `/seafarer-registrations/${id}/submit`, method: 'POST' }),
        invalidatesTags: (_r, error, id) => (error ? [] : [LIST, item(id)]),
      }),

      // --------------------------------------------------------------- review
      listSeafarerRegistrations: builder.query<
        { total: number; items: SeafarerRegistration[] },
        SeafarerRegistrationListFilter
      >({
        query: (params) => ({ url: '/seafarer-registration-review', params }),
        providesTags: () => [LIST],
      }),

      getSeafarerRegistrationReview: builder.query<
        { registration: SeafarerRegistration; attachments: Attachment[] },
        string
      >({
        query: (id) => ({ url: `/seafarer-registration-review/${id}` }),
        providesTags: (_r, _e, id) => [item(id)],
      }),

      approveSeafarerRegistration: builder.mutation<
        SeafarerRegistration,
        { id: string; remark?: string }
      >({
        query: ({ id, ...body }) => ({
          url: `/seafarer-registration-review/${id}/approve`,
          method: 'POST',
          body,
        }),
        invalidatesTags: (_r, error, { id }) => (error ? [] : [LIST, item(id)]),
      }),

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

      requestSeafarerRegistrationChanges: builder.mutation<
        SeafarerRegistration,
        { id: string; remark: string }
      >({
        query: ({ id, ...body }) => ({
          url: `/seafarer-registration-review/${id}/request-changes`,
          method: 'POST',
          body,
        }),
        invalidatesTags: (_r, error, { id }) => (error ? [] : [LIST, item(id)]),
      }),
    }),
    overrideExisting: false,
  });

export const {
  useGetMySeafarerRegistrationQuery,
  useStartSeafarerRegistrationMutation,
  useCancelSeafarerRegistrationMutation,
  useSaveSeafarerRegistrationMutation,
  useSubmitSeafarerRegistrationMutation,
  useListSeafarerRegistrationsQuery,
  useGetSeafarerRegistrationReviewQuery,
  useApproveSeafarerRegistrationMutation,
  useRejectSeafarerRegistrationMutation,
  useRequestSeafarerRegistrationChangesMutation,
} = seafarerRegistrationApi;
