import axios from "axios";
import type { ApiError } from "../types/api/error";
import type { Engagement } from "../types/engagement";
import type { EngagementFavoriteRecipeResponse, EngagementMakeRecipeResponse, EngagementShareRecipeResponse, EngagementViewRecipeResponse } from "../types/api/engagement";
import { GetBackendUrl } from "./environment";

const BACKEND_URL = GetBackendUrl();

export async function EngagementViewRecipe(recipeId: number): Promise<Engagement | ApiError> {
  const response = await axios.post<EngagementViewRecipeResponse>(`${BACKEND_URL}/v2/api/engagement/view/${recipeId}`);

  if (response.status !== 200 || response.data.engagement === undefined) {
    const err: ApiError = {
      status: response.data.status,
      message: response.data.message
    };
    return err;
  }

  return response.data.engagement;
}

export async function EngagementShareRecipe(recipeId: number): Promise<Engagement | ApiError> {
  const response = await axios.post<EngagementShareRecipeResponse>(`${BACKEND_URL}/v2/api/engagement/share/${recipeId}`);

  if (response.status !== 200 || response.data.engagement === undefined) {
    const err: ApiError = {
      status: response.data.status,
      message: response.data.message
    };
    return err;
  }

  return response.data.engagement;
}

export async function EngagementFavoriteRecipe(recipeId: number): Promise<Engagement | ApiError> {
  const response = await axios.post<EngagementFavoriteRecipeResponse>(`${BACKEND_URL}/v2/api/engagement/favorite/${recipeId}`);

  if (response.status !== 200 || response.data.engagement === undefined) {
    const err: ApiError = {
      status: response.data.status,
      message: response.data.message
    };
    return err;
  }

  return response.data.engagement;
}

export async function EngagementMakeRecipe(recipeId: number): Promise<Engagement | ApiError> {
  const response = await axios.post<EngagementMakeRecipeResponse>(`${BACKEND_URL}/v2/api/engagement/make/${recipeId}`);

  if (response.status !== 200 || response.data.engagement === undefined) {
    const err: ApiError = {
      status: response.data.status,
      message: response.data.message
    };
    return err;
  }

  return response.data.engagement;
}
