import { authService } from './auth.service';

class ApiService {

  async fetch(path: string, options: RequestInit = {}): Promise<Response> {
    const response = await this.doFetch(path, options);

    if (response.status === 401) {
      const refreshed = await this.refresh();
      if (refreshed) {
        return this.doFetch(path, options);
      } else {
        authService.clearSession();
        window.dispatchEvent(new CustomEvent('session-expired'));
        throw new Error('Session expired');
      }
    }

    return response;
  }

  private async doFetch(path: string, options: RequestInit): Promise<Response> {
    //todo return fetch(`/api${path}`, {
    return fetch(`http://127.0.0.1:8080${path}`, {
      ...options,
      credentials: 'include',
      headers: {
        'Content-Type': 'application/json',
        ...(authService.accessToken
          ? { Authorization: `Bearer ${authService.accessToken}` }
          : {}),
        ...options.headers,
      },
    });
  }

  private async refresh(): Promise<boolean> {
    try {
      //const response = await fetch('/api/auth/refresh', {
      const response = await fetch('http://127.0.0.1:8080/auth/refresh', {
        method: 'POST',
        credentials: 'include',
      });

      if (!response.ok) return false;

      const { accessToken } = await response.json();
      authService.setSession(authService.user!, accessToken);
      return true;
    } catch {
      return false;
    }
  }
}

export const apiService = new ApiService();