import { decodeJwt } from 'jose';
import { authClient } from './auth-client';

export class ApiClient {
  private token: string | null;

  constructor() {
    this.token = null;
  }

  private tokenValid() {
    if (!this.token) {
      return false;
    }

    const jwt = decodeJwt(this.token);
    if (!jwt.exp) {
      return false;
    }

    return jwt.exp > Date.now() / 1000 + 10;
  }

  async getToken() {
    if (this.tokenValid()) {
      return this.token;
    }

    const token = (await authClient.token().then((t) => t.data?.token)) ?? null;
    this.token = token;

    return token;
  }

  async request<T>(url: string, options: RequestInit = {}): Promise<T> {
    const token = await this.getToken();

    const response = await fetch(url, {
      ...options,
      headers: {
        ...options.headers,
        Authorization: `Bearer ${token}`,
      }
    });

    const data = await response.json();
    return data;
  }
}

export const apiClient = new ApiClient();
