import { baseApi } from '../../base-api';
import type { BiometricEnrollment, EnrollBiometric } from './biometric-enrollment.types';

const TAG = 'BiometricEnrollment' as const;
const forProfile = (profileId: string) => ({ type: TAG, id: profileId }) as const;

/**
 * Scanner capture (fingerprint, face) stored per profile. No applicant-facing
 * endpoint — enrollment happens at a counter with a scanner.
 */
export const biometricEnrollmentApi = baseApi
  .enhanceEndpoints({ addTagTypes: [TAG] })
  .injectEndpoints({
    endpoints: (builder) => ({
      enrollBiometric: builder.mutation<BiometricEnrollment, EnrollBiometric>({
        query: (body) => ({ url: '/biometric-enrollments', method: 'POST', body }),
        invalidatesTags: (r, error) => (error || !r ? [] : [forProfile(r.profileId)]),
      }),

      getBiometricEnrollments: builder.query<BiometricEnrollment[], string>({
        query: (profileId) => ({ url: `/biometric-enrollments/profile/${profileId}` }),
        providesTags: (_r, _e, profileId) => [forProfile(profileId)],
      }),

      /** Self-service, view-only: the caller's own live enrollments. */
      getMyBiometricEnrollments: builder.query<BiometricEnrollment[], void>({
        query: () => ({ url: '/biometric-enrollments/mine' }),
        providesTags: [{ type: TAG, id: 'MINE' }],
      }),

      /** Dev/test only — the API reports false in production. */
      getBiometricSimulateCapabilities: builder.query<{ simulateEnabled: boolean }, void>({
        query: () => ({ url: '/biometric-enrollments/simulate/capabilities' }),
      }),

      revokeBiometricEnrollment: builder.mutation<
        BiometricEnrollment,
        { id: string; profileId: string; reason: string }
      >({
        query: ({ id, reason }) => ({
          url: `/biometric-enrollments/${id}/revoke`,
          method: 'POST',
          body: { reason },
        }),
        invalidatesTags: (_r, error, { profileId }) => (error ? [] : [forProfile(profileId)]),
      }),

      /** Stamps the profile's BSID once enrollment is confirmed. Requires an active enrollment. */
      generateBsid: builder.mutation<{ id: string; bsid: string | null }, string>({
        query: (profileId) => ({
          url: `/biometric-enrollments/profile/${profileId}/generate-bsid`,
          method: 'POST',
        }),
        invalidatesTags: (_r, error, profileId) => (error ? [] : [forProfile(profileId)]),
      }),
    }),
    overrideExisting: false,
  });

export const {
  useEnrollBiometricMutation,
  useGetBiometricEnrollmentsQuery,
  useGetMyBiometricEnrollmentsQuery,
  useGetBiometricSimulateCapabilitiesQuery,
  useRevokeBiometricEnrollmentMutation,
  useGenerateBsidMutation,
} = biometricEnrollmentApi;
