import axios from "axios";
import { CategoryDatasourceInf } from "../category_datasource";
import { Category, CategoryFormValues } from "./entities/category";
import { APIUrl } from "../../../core/constants/api_url";
import { CategoryModel } from "../../../domain/model/CategoryModel";

export class CategoryDatasourceProd implements CategoryDatasourceInf {
  /**
   * Registers a new category using the provided form data.
   * @param form - The category data to be registered.
   * @returns A promise that resolves when the category is successfully registered.
   */
  async registerCategory(form: CategoryFormValues): Promise<void> {
    await axios.post(APIUrl + "/category", {
      nameES: form.nameES,
      nameEN: form.nameEN,
    });
  }

  /**
   * Retrieves a list of categories.
   * @returns A promise that resolves to an array of Category objects.
   */
  async getCategories(): Promise<Category[]> {
    const { data: dataES } = await axios.get<CategoryModel[]>(
      APIUrl + "/category/",
      {
        params: {
          lang: "ES",
        },
      }
    );
    const { data: dataEN } = await axios.get<CategoryModel[]>(
      APIUrl + "/category/",
      {
        params: {
          lang: "EN",
        },
      }
    );
    const categories: Category[] = [];
    for (let i = 0; i < dataES.length; i++) {
      const category: Category = {
        idCategory: dataES[i].idCategory,
        nameES: dataES[i].name,
        nameEN: dataEN[i].name,
      };
      categories.push(category);
    }

    return categories;
  }

  /**
   * Deletes a category by its ID.
   * @param category - The category to be deleted.
   * @returns A promise that resolves when the category is successfully deleted.
   */
  async deleteCategory(category: Category): Promise<void> {
    await axios.delete(APIUrl + `/category/${category.idCategory}`);
  }
}
