import {ExpectedError} from '@makeflow/gateway-shared';

import {Router} from '../routes';
import {APIResult} from '../types';

export class APIService {
  constructor(private router: Router) {}

  async post<TResult = unknown>(api: string, body?: object): Promise<TResult> {
    let response = await fetch(api, {
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(body),
      method: 'POST',
      credentials: 'same-origin',
    });

    if (!response.ok) {
      throw new ExpectedError('REQUEST_FAILED_WITH_UNKNOWN_ERROR');
    }

    let {data, error}: APIResult<TResult> = await response.json();

    if (error) {
      if (error.code === 'AUTHORIZATION_REQUIRED') {
        this.router.login.$push();
      }

      throw new ExpectedError(error.code, error.message);
    }

    return data;
  }
}
