import { kbVar } from '@/config/kb/var';
import { test, expect } from '@/core/fixtures';
import { checkReport } from '@/utils/functions';
import { navigateToReports } from '@/utils/kbUtils';
import { existsSync, mkdirSync } from 'fs';
import excel from 'exceljs';

import path from 'path';
import { users } from '../../const';
import { kbEntityManager } from '@/test-data/KB';
import { Entity } from '@/core/api/types';
import { roleManager } from '@/core/api/classes';
const downloadsFolder = './downloads';

const {
  authorized: { username, password },
} = users;

let company = {} as Entity;
let company2 = {} as Entity;
let bia = {} as Entity;
test.beforeAll(async ({ api: { login } }) => {
  await login();
  await roleManager.makeUserSuperuser(username);

  const biaEntity = await kbEntityManager.createBia();
  bia = biaEntity.entity;
  company = biaEntity.entities.company;
  company2 = await kbEntityManager.create('Company');
});

test.beforeEach(async ({ page, actions: { loginAsUser } }) => {
  await page.goto('/');
  await loginAsUser(username, password);
  await expect(page).toHaveURL(/.*home/);
});
test.afterAll(async () => await kbEntityManager.flush());

test('Authorized user generates report via Bia module', async ({
  page,
  widgetHelper: w,
}) => {
  await w.tile({ label: 'Regulace' }).click();
  await w.tile({ label: 'BIA Tool' }).click();
  await w.header({ text: 'Reporty' }).isVisible();

  await w.button({ label: kbVar.val.report1 }).click();
  await w.selectInput({ label: 'Firma-Company' }).select(company.kod);
  await w
    .multiSearchInput({ label: 'Vyberte ve firmě jednu či více BIA' })
    .selectFirstBySearch(bia.nameCz);
  await w.checkboxInput({ label: 'Celá firma' }).check();
  await w.checkboxInput({ label: 'S Impact Assesmentem' }).check();
  await w.button({ label: 'Spustit generování dokumentu' }).click();
  await checkReport(page);

  await w.icon({ icon: 'file-excel' }).click();
  const download = await page.waitForEvent('download');
  mkdirSync(downloadsFolder, { recursive: true });
  const fileName = kbVar.val.report1 + '.xls';
  const filePath = path.join(downloadsFolder, fileName);
  await download.saveAs(filePath);
  expect(existsSync(filePath)).toBeTruthy();
});

test('Authorized user generates report via report module', async ({
  page,
  widgetHelper: w,
}) => {
  await navigateToReports('Modul BIA', page, w);
  await w.text({ text: kbVar.val.report2 }).click();
  await w.checkboxInput({ label: 'Všechny útvary zvolené organizace' }).check();
  await w.checkboxInput({ label: 'Včetně podútvarů' }).check();
  await w.checkboxInput({ label: 'Včetně podpůrných aplikací' }).check();
  await w
    .selectInput({
      label:
        'Organizace (použije se jen pokud je zaškrtnuta volba "Celá organizace") ',
    })
    .select('KBPS');
  await w.button({ label: 'Spustit generování dokumentu' }).click();
  await checkReport(page);

  const downloadPromise = page.waitForEvent('download');
  await page.getByTestId('icon-file-excel').click();
  const download = await downloadPromise;
  mkdirSync(downloadsFolder, { recursive: true });
  const fileName = kbVar.val.report2 + '.xls';
  const filePath = path.join(downloadsFolder, fileName);
  await download.saveAs(filePath);
  expect(existsSync(filePath)).toBeTruthy();
});

test('Check report', async () => {
  const fileName = kbVar.val.report2 + '.xls';
  const filePath = path.join(downloadsFolder, fileName);

  expect(existsSync(filePath)).toBeTruthy();

  const workbook = new excel.Workbook();
  await workbook.xlsx.readFile(filePath);
  const worksheet = workbook.getWorksheet(1); // První list

  if (!worksheet) {
    throw new Error('Worksheet must be defined ');
  }
  // Ověření, že soubor obsahuje data
  expect(worksheet.rowCount).toBeGreaterThan(0);
  expect(worksheet.getRow(1).cellCount).toBeGreaterThan(0);
});
