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

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

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

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

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

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

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

export default JobAdApi;
