/* eslint-disable no-console */
import Event from "@models/Event";
import {
  APIPath,
} from "./backend";
import {
  authedGetBackendAPI, authedPostBackendAPI, authedDeleteBackendAPI, authedPutBackendAPI,
} from "./auth";

interface Options {
  limit?: number;
  offset?: number;
  auth?: boolean;
  since?: Date;
}

class EventApi {
  static getEvent = async (id: number, auth = false): Promise<Event> => {
    try {
      return await authedGetBackendAPI<Event>({
        path: APIPath.EVENTS, urlParams: { id }, authenticated: auth,
      });
    } catch (err) {
      console.error(err);
      throw err;
    }
  };

  static getEvents = async ({
    since, limit, offset, auth = false,
  }: Options = {}): Promise<Event[]> => {
    try {
      return await authedGetBackendAPI<Event[]>({
        path: APIPath.EVENTS,
        queryParams: {
          since,
          limit,
          offset,
        },
        authenticated: auth,
      });
    } catch (err) {
      console.error(err);
      throw err;
    }
  };

  static createEvent = async (data: Event): Promise<Event> => {
    try {
      return await authedPostBackendAPI<Event, Event>({
        path: APIPath.EVENTS,
      }, data);
    } catch (err) {
      console.error(err);
      throw err;
    }
  };

  static updateEvent = async (data: Event): Promise<Event> => {
    try {
      return await authedPutBackendAPI<Event, Event>({
        path: APIPath.EVENTS, urlParams: { id: data.id },
      }, data);
    } catch (err) {
      console.error(err);
      throw err;
    }
  };

  static deleteEvent = async (id: number): Promise<void> => {
    try {
      await authedDeleteBackendAPI<{ message: "OK" }>({ path: APIPath.EVENTS, urlParams: { id } });
    } catch (err) {
      console.error(err);
      throw err;
    }
  };
}

export default EventApi;
