import { baseAPI } from "@/Shared/API/baseAPI";
import { getTokens } from "@/Shared/helpers/getTokens";
import axios, { AxiosError } from "axios";

class CreateReview {
  response: string;
  isLoading: boolean;
  error: string;
  constructor() {
    this.response = "";
    this.isLoading = false;
    this.error = "";
  }

  async createReview(
    endpoint: string,
    id: number | null | undefined,
    review: string
  ) {
    try {
      this.isLoading = true;

      const access_token = getTokens()?.access_token;

      const Authorization = `Bearer ${access_token}`;

      const config = {
        headers: {
          Authorization,
        },
      };

      const body = {
        review,
      };

      const response = await axios.post(
        `${baseAPI}/${endpoint}/${id}/reviews/`,
        body,
        config
      );

      this.response = response.data;

      console.log(response);
    } catch (error: unknown) {
      console.log(error);
      if (error instanceof AxiosError) {
        this.error = error.message;
      } else {
        this.error = "An error ocured";
      }
    } finally {
      this.isLoading = false;
    }
  }
}

export const createReviewAction = new CreateReview();
