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 });
  }

  /** Select the first non-placeholder option in the Unit dropdown. */
  async selectFirstUnit() {
    const select = this.unitSelect;
    // Wait for at least one real option to load (beyond the placeholder)
    await select.locator("option:not([value=''])").first().waitFor({ state: "attached" });
    const options = select.locator("option");
    const count = await options.count();
    for (let i = 0; i < count; i++) {
      const value = await options.nth(i).getAttribute("value");
      if (value && value !== "") {
        await select.selectOption({ index: i });
        return;
      }
    }
  }

  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);
  }
}
