import { baseApi } from '../../base-api';
import type {
  CreateVesselIncident,
  Vessel,
  VesselIncident,
  VesselReport,
  VesselReportQuery,
  VesselStatus,
} from './vessel.types';

const TAGS = ['Vessel', 'VesselIncident'] as const;

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

/**
 * The vessel register (module 11). Registration applications themselves go
 * through `licensingApi` as the VESSEL_REGISTRATION type; these endpoints
 * serve the register the certificates produce.
 */
export const vesselApi = baseApi
  .enhanceEndpoints({ addTagTypes: TAGS })
  .injectEndpoints({
    endpoints: (builder) => ({
      getMyVessels: builder.query<Vessel[], void>({
        query: () => ({ url: '/vessels/mine' }),
        providesTags: () => [listTag('Vessel')],
      }),

      getVessels: builder.query<
        { total: number; items: Vessel[] },
        { search?: string } | void
      >({
        query: (args) => ({
          url: '/vessels',
          params: args?.search ? { search: args.search } : undefined,
        }),
        providesTags: () => [listTag('Vessel')],
      }),

      /**
       * The whole backoffice dashboard in one call — KPIs, time series,
       * breakdowns and worklists. Backoffice only (`can:View:vessel-registry`).
       *
       * Array filters are passed as arrays, not joined strings: the API accepts
       * both the repeated and the comma-separated form, and `params` serialises
       * the repeated one.
       */
      getVesselReport: builder.query<VesselReport, VesselReportQuery | void>({
        query: (params) => ({
          url: '/vessels/report',
          params: params ?? undefined,
        }),
        providesTags: () => [listTag('Vessel')],
      }),

      getVessel: builder.query<Vessel, string>({
        query: (id) => ({ url: `/vessels/${id}` }),
        providesTags: (_r, _e, id) => [{ type: 'Vessel', id }],
      }),

      /** Suspend / deregister / reinstate with a mandatory reason. */
      updateVesselStatus: builder.mutation<
        Vessel,
        { vesselId: string; status: VesselStatus; reason: string }
      >({
        query: ({ vesselId, ...body }) => ({
          url: `/vessels/${vesselId}/status`,
          method: 'POST',
          body,
        }),
        invalidatesTags: (_r, error, { vesselId }) =>
          error ? [] : [listTag('Vessel'), { type: 'Vessel', id: vesselId }],
      }),

      getVesselIncidents: builder.query<VesselIncident[], string>({
        query: (vesselId) => ({ url: `/vessels/${vesselId}/incidents` }),
        providesTags: () => [listTag('VesselIncident')],
      }),

      createVesselIncident: builder.mutation<
        VesselIncident,
        { vesselId: string; body: CreateVesselIncident }
      >({
        query: ({ vesselId, body }) => ({
          url: `/vessels/${vesselId}/incidents`,
          method: 'POST',
          body,
        }),
        invalidatesTags: (_r, error) =>
          error ? [] : [listTag('VesselIncident')],
      }),
    }),
  });

export const {
  useGetMyVesselsQuery,
  useGetVesselsQuery,
  useGetVesselReportQuery,
  useGetVesselQuery,
  useUpdateVesselStatusMutation,
  useGetVesselIncidentsQuery,
  useCreateVesselIncidentMutation,
} = vesselApi;
