import store from '@/store';

const setHeaders = (headers: HeadersInit | undefined, token: string | undefined) => {
  if (!headers && !!token) {
    return { Authorization: `Bearer ${token}` };
  }
  if (!!headers && !token) {
    return headers;
  }
  if (!!headers && !!token) {
    return {
      ...headers,
      Authorization: `Bearer ${token}`,
    };
  }
  return {};
};

class SignetRequestController {
  get = async <T>(endpoint: string): Promise<T | null> => {
    const resp = await fetch(
      `/api/${endpoint}`,
      {
        method: 'GET',
        headers: setHeaders(
          undefined,
          store.getters.getToken,
        ),
      },
    );
    if (resp.status === 404) {
      return null;
    }
    return await resp.json() as Promise<T>;
  };

  post = async <T1, T2>(endpoint: string, payload: T2): Promise<T1 | null> => {
    const resp = await fetch(
      `/api/${endpoint}`,
      {
        method: 'POST',
        body: JSON.stringify(payload),
        headers: setHeaders(
          { 'Content-Type': 'application/json' },
          store.getters.getToken,
        ),
      },
    );
    if (resp.status === 404) {
      return null;
    }
    return await resp.json() as Promise<T1>;
  };
}

export default SignetRequestController;
