/* eslint-disable no-console */
import JobAd from "@models/JobAd";
import {
  APIPath, deleteBackendAPI, getBackendAPI, postBackendAPI, putBackendAPI,
} from "./backend";

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

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

  static getJobAds = async ({
    since, limit, offset, auth,
  }: Options = {}): Promise<JobAd[]> => {
    try {
      return await getBackendAPI<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 postBackendAPI<JobAd, JobAd>({
        path: APIPath.JOBADS, authenticated: true,
      }, data);
    } catch (err) {
      console.error(err);
      throw err;
    }
  };

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

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

export default JobAdApi;
