import { roleManager } from '@/core/api/classes';
import { Entity } from '@/core/api/types';
import { expect, test } from '@/core/fixtures';
import { kbEntityManager } from '@/test-data/KB';
import { users } from '@/tests/KB/const';

const user = users.authorized;

let person = {} as Entity;
let company = {} as Entity;
let orgUnit = {} as Entity;
let logicalProcessDomain = {} as Entity;
let capabilityDomain = {} as Entity;

test.beforeAll(async ({ api: { login } }) => {
  await login();
  await roleManager.makeUserSuperuser(user.username);
  const orgUnitData = await kbEntityManager.createOrgUnit();
  person = orgUnitData.entities.person;
  company = orgUnitData.entities.company;
  orgUnit = orgUnitData.entity;

  logicalProcessDomain = await kbEntityManager.createWithRelations(
    'LogicalProcessDomain',
    {},
    {},
    {
      logicaldomainRoot: [
        'LogicalDomainRoot',
        kbEntityManager.make('LogicalDomainRoot'),
      ],
    }
  );

  capabilityDomain = await kbEntityManager.create('CapabilityDomain', {
    firma: company.gid,
  });
});

test.afterAll(async () => await kbEntityManager.flush());

test('Create Capability', async ({
  page,
  widgetHelper: w,
  actions: { loginAsUser },
}) => {
  await page.goto('/');
  await loginAsUser(user.username, user.password);
  await w.tile({ label: 'Capability' }).click();
  await w.tile({ label: 'Capability' }).click();
  await w.dataTable().singleAction({ label: 'Přidat capabilitu' }).click();

  await w
    .searchInput({ label: 'Logická subdoména' })
    .selectFirstBySearch(logicalProcessDomain.nameCz);
  await w.selectInput({ label: 'Firma' }).select(company.kod);
  await w
    .searchInput({ label: 'Capability domain' })
    .selectFirstBySearch(capabilityDomain.nameCz);
  await w.textInput({ label: 'Kód' }).change(company.kod);
  await w
    .textInput({ label: 'Název Capability ' })
    .change('PW test capability name');

  await w.button({ label: 'Vytvořit capabilitu' }).click();

  await w.header({ text: company.kod }).isVisible();
  expect(page.url()).toContain('gui/Capability/detail');
});
