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

function exactPattern(name: string | RegExp) {
  if (name instanceof RegExp) return name;
  return new RegExp(`^${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}$`);
}

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

  async goto(id: string) {
    await this.page.goto(`/user-management/role/${id}/edit`);
  }

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

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

  permissionOption(name: string | RegExp) {
    return this.page.locator("label").filter({ hasText: exactPattern(name) });
  }

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

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