import { roleManager } from '@/core/api/classes';
import { ReportScenario } from '@/core/scenarios/Report';
import { WidgetHelper } from '@/core/WidgetHelper';
import { kbEntityManager } from '@/test-data/KB';
import { kbEntityGenerator } from '@/test-data/KB/api';
import { users } from '@/tests/KB/const';
import { test } from '@core/fixtures';
import { Page } from 'playwright';

const user = users.authorized;
test.beforeAll(async ({ api: { login } }) => {
  await login();
  await kbEntityManager.flush();
});

test('Report "EAM12 - Analytika"', async ({
  page,
  widgetHelper: wh,
  actions,
  api: { login },
}, testInfo) => {
  (await login(),
    await roleManager.makeUserSuperuser(user.username),
    await roleManager.addRoleToUser(user.username, 'BIA_ADMIN'));

  await ReportScenario.makeAndRun({
    context: { page, widgetHelper: wh, actions, testInfo },
    user,
    navigateParams: {
      module: 'Modul BIA',
      reportName: 'BIA12 - Analytika',
    },
    generateTestData: async () => {
      const entities = await kbEntityGenerator([
        {
          type: 'Company',
          name: 'companyKB',
          data: {
            kod: 'KB',
            nazev: 'Komerční banka',
          },
          priority: 1,
        },

        // ------ OrgUnit

        {
          type: 'OrgUnit',
          name: 'orgunit1',
          data: {
            firma: ({ companyKB }) => companyKB.gid,
            nazev: 'Korporátní a Municipální bankovnictví',
            kod: '2006',
            jiraId: '',
            typUtvaru: 'ARM',
            nazevEn: 'ARM One',
            egjeKod: '02006.016',
            unitId: '2006',
          },
        },
        {
          type: 'OrgUnit',
          name: 'orgunit2',
          data: {
            firma: ({ companyKB }) => companyKB.gid,
            nazev: 'Korporátní centrum - Praha 1',
            kod: '72300',
            unitId: '902019',
            typUtvaru: 'UNIT',
            egjeKod: '72300.300',
            notInEgje: '1',
            notInJira: '1',
            nadrazenyUtvar: ({ orgunit1 }) => orgunit1.gid,
          },
        },
        {
          type: 'OrgUnit',
          name: 'orgunit21',
          data: {
            firma: ({ companyKB }) => companyKB.gid,
            nazev: 'Customer Tribe',
            typUtvaru: 'TRIBE',
            kod: 'cod8931',
            egjeKod: '8931.16',
            unitId: '8931',
            jiraId: '8931',
          },
        },
        {
          type: 'OrgUnit',
          name: 'orgunit22',
          data: {
            firma: ({ companyKB }) => companyKB.gid,
            nazev: 'Client & Onboarding Process',
            kod: 'SQ-36271',
            egjeKod: '',
            unitId: '905',
            typUtvaru: 'SQUAD',
            jiraId: '36271',
            nadrazenyUtvar: ({ orgunit21 }) => orgunit21.gid,
          },
        },

        // ------ EaPerson

        {
          type: 'EaPerson',
          name: 'person1',
          data: {
            oscis: '602235',
            username: 'bashful', // BIA_READER (nebo jiný)
            lastName: 'Dwarf',
            firstName: 'Bashful',
            position: 'Development Engineer',
            email: 'sneezy.dwarf@kb.com',
            mobile: '420602235024',
            orgUnitCode: ({ orgunit2 }) => orgunit2.unitId,
          },
        },
        {
          type: 'EaPerson',
          name: 'person2',
          data: {
            oscis: '420602',
            username: 'grumpy', // BIA_UPDATER
            lastName: 'Dwarf',
            firstName: 'Grumpy',
            position: 'Development Engineer',
            email: 'happy.dwarf@kb.com',
            mobile: '420602235024',
            orgUnitCode: ({ orgunit2 }) => orgunit2.unitId,
          },
        },
        {
          type: 'EaPerson',
          name: 'person3',
          data: {
            oscis: '420586',
            username: 'doc', // BIA_ADMIN
            lastName: 'Dwarf',
            firstName: 'Doc',
            position: 'Procesní analytik',
            email: 'doc.dwarf@kb.com',
            mobile: '420602235024',
            orgUnitCode: ({ orgunit2 }) => orgunit2.unitId,
          },
        },

        // ------ CapabilityDomain

        {
          type: 'CapabilityDomain',
          name: 'capabilitydomain1',
          data: {
            nameCz: 'Řízení trhu, nabídky a poptávky',
            kod: 'D1',
            domainObjectCz: 'Trh, nabídka, poptávka',
            company: 'KB',
            firma: ({ companyKB }) => companyKB.gid,
          },
        },
        {
          type: 'CapabilityDomain',
          name: 'capabilitydomain11',
          data: {
            nameCz: 'Řízení informací o trhu',
            kod: 'D11',
            domainObjectCz: 'Trh',
            parentDomain: ({ capabilitydomain1 }) => capabilitydomain1.gid,
          },
        },
        {
          type: 'CapabilityDomain',
          name: 'capabilitydomain111',
          data: {
            nameCz: 'Analýza tržních informací',
            kod: 'D111',
            domainObjectCz: 'Trh',
            parentDomain: ({ capabilitydomain11 }) => capabilitydomain11.gid,
          },
        },

        // ------ Capability

        {
          type: 'Capability',
          name: 'capability1',
          data: {
            nazevCz: 'Capabilita direct bankingu pro corporátní management',
            nazevEn: 'Direct banking products Corp. Cash management',
            code: 'D420.69',
            wfState: '100',
            vlastnik: ({ orgunit21 }) => orgunit21.gid,
            spravce: ({ orgunit22 }) => orgunit22.gid,
            domena: ({ capabilitydomain111 }) => capabilitydomain111.gid,
          },
        },

        // ------ ApplicationFolder (nutné pro Application)

        {
          type: 'ApplicationFolder',
          name: 'appFolder1',
          data: {
            title: 'KB Applications Test',
            companyDirect: 'KB',
            registryCodeDirect: 'APP,APG',
          },
          priority: 1,
        },

        // ------ Application

        {
          type: 'Application',
          name: 'app1',
          data: {
            kod: 'CORE-BANK',
            nazevCz: 'Core Banking System',
            appPackage: ({ appFolder1 }) => appFolder1.gid,
            stavAplikace: 'in operation',
            wfState: '020',
            vlastnik: ({ orgunit21 }) => orgunit21.gid, // Customer Tribe
            spravce: ({ orgunit22 }) => orgunit22.gid, // Client & Onboarding Squad
          },
        },

        // ------ LogicalDomainRoot

        {
          type: 'LogicalDomainRoot',
          name: 'ldr1',
          data: {
            // možná prázdné, záleží na factory
          },
          priority: 2,
        },

        // ------ LogicalBusinessObject

        {
          type: 'LogicalBusinessObject',
          name: 'lbo1',
          data: {
            domainRoot: ({ ldr1 }) => ldr1.gid,
            code: 'LO-TEST',
            nameCz: 'Testovací business objekt',
          },
          priority: 1,
        },

        // ------ ProcesniBia

        {
          type: 'ProcesniBia',
          name: 'bia1',
          data: {
            kod: 'BIA-2024',
            nameCz: 'BIA Test 2024',
            firma: ({ companyKB }) => companyKB.gid,
            bcmManagers: ({ person1 }) => [`person-${person1.oscis}`],
            wfState: '100',
          },
          // priority: 1,
        },

        // ------ Agendy

        {
          type: 'Agenda',
          name: 'agenda1',
          data: {
            kod: 'AG-1',
            nazevCz: 'BigBangTheory',
            stav: 'VPROVOZU',
            biaKriticnost: 'vital',
            capabilita: ({ capability1 }) => capability1.gid,
            procesniBia: ({ bia1 }) => bia1.gid,
            // biaZpracovatel: ({ person1 }) => [person1.gid],
            // biaValidator: ({ person1 }) => person1.gid,
            // biaSchvalovatel: ({ person1 }) => person1.gid,
            'Business object': ({ lbo1 }) => lbo1.gid,
          },
        },

        // ------ AgendaXApplication

        {
          type: 'AgendaXApplication',
          name: 'agnXApp1',
          data: {
            uzivajiciAgenda: ({ agenda1 }) => agenda1.gid,
            uzivanaAplikace: ({ app1 }) => app1.gid,
            vyznamnost: 'vital', // BiaImportance: vital/important/support
            // pozadovaneRTO: ...,            // gid na Rto entitu (pokud existuje)
            // pozadovaneRPO: ...,            // gid na Rpo entitu (pokud existuje)
          },
        },
      ]);

      // ------ Update

      await kbEntityManager.update('Agenda', entities.get('agenda1').gid, {
        biaZpracovatel: [`person-${entities.get('person1').oscis}`],
        biaValidator: `person-${entities.get('person1').oscis}`,
        biaSchvalovatel: `person-${entities.get('person2').oscis}`,
      });

      await kbEntityManager.update('ProcesniBia', entities.get('bia1').gid, {
        bcmManagers: [`person-${entities.get('person3').oscis}`],
      });

      return entities;
    },

    // klikací testování
    async fillReportFormFunc() {
      await page.goto('/');
      await actions.logOut();
      await actions.loginAsUser('doc', 'doc');
      await wh.tile({ label: 'Regulace' }).click();
      await wh.tile({ label: 'BIA Tool' }).click();
      await wh.tile({ label: 'Bia Procesní' }).click();
      await wh.dataTable().body.firstRow.click();
      await wh.tabBar().navigateToTab('Validace');
      await page
        .getByText('Stav: 100 - BIA vytvořena')
        .waitFor({ state: 'visible' });
      await page.locator('[label="Stav: 100 - BIA vytvořena"]').click();
      await page
        .getByText('Spustit zpracování BIA')
        .waitFor({ state: 'visible' });
      await page.locator('[label="Spustit zpracování BIA"]').click();
      await actions.logOut();
      await actions.loginAsUser('bashful', 'bashful');
      await page.getByText('Zpracováno').waitFor({ state: 'visible' });
      await page.locator('[label="Zpracováno"]').click();
      await page.getByText('Validovat').waitFor({ state: 'visible' });
      await page.locator('[label="Validovat"]').click();
      await actions.logOut();
      await actions.loginAsUser('grumpy', 'grumpy');
      await page.getByText('Schválit').waitFor({ state: 'visible' });
      await page.locator('[label="Schválit"]').click();
      await actions.logOut();
      await actions.loginAsUser('doc', 'doc');
      await page
        .getByText('Stav: 500 - Validace BCM Managerem')
        .waitFor({ state: 'visible' });
      await page
        .locator('[label="Stav: 500 - Validace BCM Managerem"]')
        .click();
      await page
        .getByText('BIA OK (BCM Manager s BIA souhlasí)')
        .waitFor({ state: 'visible' });
      await page
        .locator('[label="BIA OK (BCM Manager s BIA souhlasí)"]')
        .click();
      await page.goto('/');
      await actions.logOut();
      await actions.loginAsUser('e2e_test', 'e2e_test');
      await wh.tile({ label: 'Administrace' }).click();
      await wh.tile({ label: 'Reporty' }).click();
      await wh.collapsible({ label: 'Modul: Modul BIA' }).toggle();
      await page.locator('tr', { hasText: 'BIA12 - Analytika' }).click();
    },

    verifyExcelFileData(api, excelApi) {
      const { rowExists, cellContain } = excelApi;

      /*
      // DEBUG - pouze pro testovací účely
      const { workbook } = excelApi;
      const worksheet = workbook.getWorksheet(1);
      if (!worksheet) {
        console.log('Worksheet nenalezen!');
        return;
      }
      console.log('=== OBSAH EXCELU ===');
      console.log('Počet řádků:', worksheet.rowCount);
      for (let row = 1; row <= Math.min(20, worksheet.rowCount); row++) {
        const rowData = worksheet.getRow(row);
        const values: string[] = [];
        rowData.eachCell({ includeEmpty: true }, (cell, colNumber) => {
          values.push(`[${colNumber}]: ${cell.text}`);
        });
        console.log(`Řádek ${row}: ${values.join(' | ')}`);
      }
      console.log('====================');
      // DEBUG - konec
      */

      test.step('Kontrola počtu řádků', () => {
        rowExists(1, 4);
      });

      test.step('Kontrola záhlaví', () => {
        cellContain(1, 1, 1, 'BIA_NAMESPACE');
        cellContain(1, 1, 2, 'BIA_TITLE');
        cellContain(1, 1, 3, 'AGENDA_TITLE');
        cellContain(1, 1, 4, 'LAST_PROCESSING_DATE');
        cellContain(1, 1, 5, 'LAST_PROCCED_BY');
        cellContain(1, 1, 6, 'LAST_VALIDATION_DATE');
        cellContain(1, 1, 7, 'LAST_VALIDATED_BY');
        cellContain(1, 1, 8, 'LAST_APPROVING_DATE');
        cellContain(1, 1, 9, 'LAST_APPROVED_BY');
        cellContain(1, 1, 10, 'LAST_BCM_MANAGER_CONFIRMATION_DATE');
        cellContain(1, 1, 11, 'LAST_BCM_MANGER');
        cellContain(1, 1, 12, 'BIA_SG_ERLCODE');
      });

      test.step('Kontrola datového řádku', () => {
        const { bia1, agenda1, person1, person2, person3 } = api.data;

        const today = new Date();
        const dateFormatted = `${today.getDate().toString().padStart(2, '0')}.${(today.getMonth() + 1).toString().padStart(2, '0')}.${today.getFullYear()}`;
        const dateISO = today.toISOString().split('T')[0]; // 2025-12-12

        const personName = (person: any) =>
          `${person.lastName} ${person.firstName}`;

        cellContain(1, 2, 1, 'sg');
        cellContain(1, 2, 2, 'BIA-001 - BIA Test 2024');
        cellContain(1, 2, 3, `${agenda1.kod} - ${agenda1.nazevCz}`);
        cellContain(1, 2, 4, dateFormatted);
        cellContain(1, 2, 5, personName(person1)); // Bashful
        cellContain(1, 2, 6, dateFormatted);
        cellContain(1, 2, 7, personName(person1)); // Bashful
        cellContain(1, 2, 8, dateFormatted);
        cellContain(1, 2, 9, personName(person2)); // Grumpy
        cellContain(1, 2, 10, dateISO);
        cellContain(1, 2, 11, personName(person3)); // Doc
        cellContain(1, 2, 12, '');
      });
    },
  });
});
