import { Page, expect } from "@playwright/test";
import setQuantity, { type LegacyUnitName } from "../setQuantity";

export default async function markIngredientAsInStock(
  page: Page,
  ingredientTitle: string,
  unit: LegacyUnitName,
  quantity?: number,
): Promise<void> {
  const bottomSheet = page.getByRole("dialog", {
    name: new RegExp(ingredientTitle),
  });

  // Click "Отметить, что уже есть" from context menu
  // Wait for the context menu to be stable before clicking
  const markAsAvailableButton = bottomSheet.getByRole("button", {
    name: /Отметить, что уже есть/,
  });
  await markAsAvailableButton.waitFor({ state: "visible" });
  await markAsAvailableButton.click({ force: true });

  // Wait for the "Добавить кол-во" modal to appear
  await expect(
    page.getByRole("heading", { name: "Добавить кол-во" }),
  ).toBeVisible({
    timeout: 5000,
  });

  // Set the quantity
  await setQuantity(page, unit, quantity);

  // Submit the form
  await page.getByRole("button", { name: "Подтвердить" }).click();

  // Wait for the modal to close
  await expect(
    page.getByRole("heading", { name: "Добавить кол-во" }),
  ).not.toBeVisible({
    timeout: 5000,
  });
}
