import type { Page } from "@playwright/test";

export class ProductCreateFormPage {
  private page: Page;
  constructor(page: Page) {
    this.page = page;
  }

  async goto() {
    await this.page.goto("/product/product/create");
  }

  get codeInput() {
    return this.page.getByLabel("Code");
  }

  get nameInput() {
    return this.page.getByLabel("Name");
  }

  get descriptionInput() {
    return this.page.getByLabel("Description");
  }

  get unitSelect() {
    return this.page.getByLabel("Unit");
  }

  get submitButton() {
    return this.page.getByRole("button", { name: /create|save/i });
  }

  get cancelButton() {
    return this.page.getByRole("button", { name: /cancel/i });
  }

  /** Open the Unit combobox and select the first available option. */
  async selectFirstUnit() {
    await this.unitSelect.click();
    const firstOption = this.page.getByRole("option").first();
    await firstOption.waitFor({ state: "visible" });
    // Select via keyboard — clicking can miss when a long option list pushes
    // items outside the popover's viewport.
    await this.page.keyboard.press("Home");
    await this.page.keyboard.press("Enter");
  }

  async fill(fields: { code?: string; name?: string; description?: string }) {
    if (fields.code) await this.codeInput.fill(fields.code);
    if (fields.name) await this.nameInput.fill(fields.name);
    if (fields.description) await this.descriptionInput.fill(fields.description);
  }
}
