import { buildTRestClients, Interceptor } from '@jig-software/trest-client';
import { getDefaultStore } from 'jotai';
import { tokenAtom } from '../auth/client';
import {
  attendanceContract,
  holidayContract,
  leaveApplicationContract,
  leaveCancellationContract,
  leaveContract,
  leaveCreditApplicationContract,
  leaveTransactionContract,
  reportFileContract,
  staffContract,
} from './api';

const store = getDefaultStore();

const authInterceptor: Interceptor = async (ctx, next) => {
  const headers = (ctx.request.headers ??= {});
  headers['authorization'] = `Bearer ${store.get(tokenAtom) ?? ''}`;
  await next();
};

export const soriAPIClient = buildTRestClients(
  {
    attendances: attendanceContract,
    leaveApplications: leaveApplicationContract,
    leaveCancellations: leaveCancellationContract,
    leaveCreditApplications: leaveCreditApplicationContract,
    leaveTransactions: leaveTransactionContract,
    reportFiles: reportFileContract,
    staffs: staffContract,
    holidays: holidayContract,
    leaves: leaveContract,
  },
  (c) => c.baseUrl('/api').interceptors(authInterceptor),
);
