import { StoredCommand } from '../types';

const API_ROOT = window.location.href.includes('localhost')
  ? 'http://localhost:3001/api'
  : 'https://wavtool.com/api';

const showUnverfiedCode = window.location.href.includes('show-unverified-code');

const post = async (path: string, body?: {[key: string]: any}) => {
  const response = await fetch(
    `${API_ROOT}/${path}`,
    {
      method: 'POST',
      credentials: 'include',
      headers: {
        'Content-Type': 'application/json;charset=utf-8',
      },
      body: body && JSON.stringify(body),
    }
  );
  return await response.json();
}

export default {
  save: (command: Omit<StoredCommand, 'id'> & { id: number | undefined }) => post('save', { command }),
  list: (lastCommandId?: string) => post('list', { lastCommandId, showUnverfiedCode }),
  whoami: () => post('whoami')
}
