import { sentinelClient } from '@better-auth/infra/client';
import { inferAdditionalFields } from 'better-auth/client/plugins';
import { createAuthClient } from 'better-auth/react';
import * as api from './api';

const apiBaseUrl = api.apiBaseUrl;

const infraPlugins = import.meta.env.VITE_BETTER_AUTH_INFRA === 'true' ? [sentinelClient()] : [];

export const authClient = createAuthClient({
  baseURL: apiBaseUrl,
  fetchOptions: {
    credentials: 'include',
  },
  plugins: [
    ...infraPlugins,
    inferAdditionalFields({
      user: {
        phone: {
          type: 'string',
          required: false,
        },
        role: {
          type: 'string',
          required: false,
        },
        banned: {
          type: 'boolean',
          required: false,
        },
        bannedAt: {
          type: 'string',
          required: false,
        },
        banReason: {
          type: 'string',
          required: false,
        },
      },
    }),
  ],
});

export class ApiClientError extends Error {
  status?: number;
  details?: unknown;
  causeError?: unknown;

  constructor(
    message: string,
    options?: { status?: number; details?: unknown; causeError?: unknown }
  ) {
    super(message);
    this.name = 'ApiClientError';
    this.status = options?.status;
    this.details = options?.details;
    this.causeError = options?.causeError;
  }
}

export const apiClient = {
  plans: api.plans,
  user: api.user,
  complexes: api.complexes,
  sports: api.sports,
  courts: api.courts,
  admin: api.admin,
  publicBookings: {
    getAvailability: api.getAvailability,
    create: api.createPublic,
    getConfirmation: api.getConfirmation,
    cancelPublic: api.cancelPublic,
  },
  adminBookings: {
    listByComplex: api.listByComplex,
    create: api.createAdmin,
    createRecurring: api.createRecurring,
    cancelRecurringGroup: api.cancelRecurringGroup,
    listRecurringGroups: api.listRecurringGroups,
    updateRecurringGroup: api.updateRecurringGroup,
    updateStatus: api.updateStatus,
  },
};

export type { ErrorHandlers } from './api';
export { configureApiClient } from './api';

export function setApiAccessToken(_token: string | null) {
  // accessToken = token;
}

export type ApiClient = typeof apiClient;
