/* eslint-disable no-console */
import axios from "axios";
import Post from "@models/Feed";
import { getAuthHeader } from "@utils/auth";

export const URL = `${process.env.NEXT_PUBLIC_API_URL}/feed/`;

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

class FeedApi {
  static async getFeed(options: Options = {}): Promise<Post[]> {
    const {
      limit, offset, auth,
    } = options;
    const params = {
      limit,
      offset,
    };
    const headers = auth ? { Authorization: getAuthHeader() } : null;
    try {
      const resp = await axios.get(URL, { params, headers });
      return resp.data.results;
    } catch (err) {
      console.error(err);
      throw err;
    }
  }

  static async getPost(id: number, options: Options = {}): Promise<Post> {
    const { auth } = options;
    const headers = auth ? { Authorization: getAuthHeader() } : null;
    try {
      const resp = await axios.get(`${URL}${id}/`, { headers });
      return resp.data;
    } catch (err) {
      console.error(err);
      throw err;
    }
  }

  static async createPost(data: Post): Promise<Post> {
    try {
      const resp = await axios.post(URL, data, {
        headers: {
          Authorization: getAuthHeader(),
        },
      });
      return resp.data;
    } catch (err) {
      console.error(err);
      throw err;
    }
  }

  static async updatePost(data: Post): Promise<Post> {
    try {
      const putUrl = `${URL}${data.id}/`;
      const resp = await axios.put(putUrl, data, {
        headers: {
          Authorization: getAuthHeader(),
        },
      });
      return resp.data;
    } catch (err) {
      console.error(err);
      throw err;
    }
  }

  static async deletePost(id: number) {
    try {
      const resp = await axios.delete(`${URL}${id}`, {
        headers: {
          Authorization: getAuthHeader(),
        },
      });
      return resp.data;
    } catch (err) {
      console.error(err);
      throw err;
    }
  }
}

export default FeedApi;
