import { test, expect } from '../../../fixtures/index';
import { LoginPage } from '../../../pom/login.page';
import { CasePage } from '../../../pom/case/case.page';
import { extractIdFromUrl, randomString, randomText } from '../../../utils/array';
import { getTodayInTimeZone, randomDate } from '../../../pom/utils/utlisFunc';
import { verifyScreenshot } from '../../../utils/screenshot';
import path from 'path';

test.describe('Case Module - CRUD Operations', async () => {
  let loginPage: LoginPage;
  let casePage: CasePage;

  test.beforeEach(async ({ page, conf }) => {
    loginPage = new LoginPage(page);
    casePage = new CasePage(page);
    casePage.loadBusinessNames(conf.data.business_singular, conf.data.business_plural);

    await loginPage.open();
    await loginPage.login(conf.data.username, conf.data.password);
    await expect(loginPage.baseLoc.dashboardContainer).toBeVisible();
    await casePage.open();

  });

  test("CASE_010 - Verify when create new case with new client", {
    tag: ['@CASE_010', '@case', '@function']
  }, async ({ conf, apiHelper }) => {
    let caseID: string;
    const uniqueBusiness = `Business New ${randomString(8)}`
    const randomName = `${conf.data.detail.client_name} ${randomString(5)}`;
    const email = `${randomName.trim().toLowerCase().replaceAll(" ", "")}@gmail.com`;
    const expectDataPreview = [randomName, conf.data.create_client.birthday, conf.data.create_client.address, email, conf.data.create_client.phone, conf.data.detail.description];

    await test.step("Fill data and fill new client", async () => {
      await casePage.caseLoc.buttonByText("New Case").click();

      //Fill new Business
      await casePage.caseLoc.create.detail.bussiness.type(uniqueBusiness, { delay: 100 });
      await expect(casePage.caseLoc.create.optionBusiness(uniqueBusiness)).toBeVisible();
      await casePage.caseLoc.create.optionBusiness(uniqueBusiness).click();

      await expect(casePage.dashboardLoc.modal.headerModal("New Business")).toBeVisible();
      await expect(casePage.dashboardLoc.modal.inputByID("autocomplete_name")).toHaveValue(uniqueBusiness);
      await casePage.dashboardLoc.buttonByText("Create").nth(1).click();

      await expect(casePage.dashboardLoc.msgCreateSuccess).toBeVisible();
      await casePage.dashboardLoc.btnClosePopupNotification.click();
      await expect(casePage.caseLoc.create.tagBusinessCreate(uniqueBusiness)).toBeVisible();

      // Fill detail case
      await casePage.fillCaseDetail(conf.data.detail, randomName, conf.data.detail.doi, true);

      //Open modal create new client
      await casePage.caseLoc.create.detail.createActive.first().click();
      await expect(casePage.dashboardLoc.modal.headerModal("New Patient")).toBeVisible();
    })

    await test.step("Add new Client and verify Preview", async () => {
      await casePage.fillDataCreateClient(conf.data.create_client, email);
      await expect(casePage.caseLoc.create.msgCreateSuccess.first()).toBeVisible();

      // Verify all preview data matches expected values
      for (let i = 0; i < casePage.infoPrev.length; i++) {
        await expect(casePage.caseLoc.create.preview.infoClient(casePage.infoPrev[i])).toContainText(expectDataPreview[i]);
      }
    });

    await test.step("Verify when create new case", async () => {
      await casePage.caseLoc.create.btnCreateCase.click();

      await expect(casePage.caseLoc.create.msgCreateSuccess.first()).toBeVisible();
      await expect(casePage.caseLoc.detail.noDataRequest).toBeVisible();
      await expect(casePage.caseLoc.detail.businessContact).toContainText(uniqueBusiness);
      caseID = extractIdFromUrl(casePage.page.url());

      // Verify activity
      const newestActivity = await casePage.getNewestActivity();
      expect(newestActivity).toContain(`created the case ${await getTodayInTimeZone()}`);
    });

    await test.step("Teardown - Archive case", async () => {
      await apiHelper.archiveCase(caseID);
    });
  });

  test("CASE_011 - Verify when create new case with exist client", {
    tag: ['@CASE_011', '@case', '@function']
  }, async ({ conf, apiHelper }) => {
    let caseID: string;
    const doi = await randomDate();
    const expectDataPreview = [conf.data.detail.client_name, conf.data.info_client.birthday, conf.data.info_client.address, conf.data.info_client.email, conf.data.info_client.phone, conf.data.detail.description];

    await test.step("Fill data and verify it in preview", async () => {
      //Fill data
      await casePage.caseLoc.buttonByText("New Case").click();
      await casePage.fillCaseDetail(conf.data.detail, conf.data.detail.client_name, doi);
      await casePage.caseLoc.detail.boxClientNameActive(conf.data.detail.client_name).click()

      // Verify data show in preview
      for (let i = 0; i < casePage.infoPrev.length; i++) {
        await expect(casePage.caseLoc.create.preview.infoClient(casePage.infoPrev[i])).toContainText(expectDataPreview[i]);
      }
    });

    await test.step("Verify when create new case", async () => {
      await casePage.caseLoc.create.btnCreateCase.click();
      await casePage.waitForSecond(1);
      await expect(casePage.caseLoc.create.msgCreateSuccess.first()).toBeVisible();
      await expect(casePage.caseLoc.detail.noDataRequest).toBeVisible();
      await expect(casePage.caseLoc.detail.businessContact).toContainText(conf.data.detail.business);
      caseID = extractIdFromUrl(casePage.page.url());

      // Verify activity
      const newestActivity = await casePage.getNewestActivity();
      expect(newestActivity).toContain(`created the case ${await getTodayInTimeZone()}`);
    });

    await test.step("Teardown - Archive case", async () => {
      await apiHelper.archiveCase(caseID);
    });
  });

  test("CASE_035 - Verify bulk edit function to change active/reference", {
    tag: ['@CASE_035', '@case', '@function']
  }, async ({ conf, apiHelper }) => {
    let customerId: string;
    let caseId1: string;
    let caseId2: string;
    const doiCase1 = await randomDate();
    const doiCase2 = await randomDate();
    const dob = await randomDate();
    const firstName = `${randomText(5)}${randomString(5)}`;
    const lastName = `${randomText(5)}${randomString(5)}`;
    const capitalize = (str: string) => str.charAt(0).toUpperCase() + str.slice(1);
    const fullName = `${capitalize(firstName)} ${capitalize(lastName)}`;

    await test.step("Precondition: Create 1 client and 2 cases with same client", async () => {
      // Create customer first
      const customerResult = await apiHelper.createCustomer({
        first_name: firstName,
        last_name: lastName,
        birthday: dob
      });
      customerId = customerResult.customer_id;

      // Create case 1 with the customer
      const case1Result = await apiHelper.createCase({
        customer_id: customerId,
        date_of_injury: doiCase1,
        category_id: conf.data.category_id
      });
      caseId1 = case1Result.case_id;

      // Create case 2 with the same customer
      const case2Result = await apiHelper.createCase({
        customer_id: customerId,
        date_of_injury: doiCase2,
        category_id: conf.data.category_id
      });
      caseId2 = case2Result.case_id;
    });

    await test.step("Verify change 2 cases to refrence", async () => {
      // Search 2 cases
      await casePage.reload();
      await casePage.dashboardLoc.table.tabInTable("Active").click();
      await casePage.search(fullName);
      await expect(casePage.dashboardLoc.table.itemInRow(caseId1)).toBeVisible();
      await expect(casePage.dashboardLoc.table.itemInRow(caseId2)).toBeVisible();
      await expect(casePage.dashboardLoc.common.pTextContainsAll('Showing 1 to 2 of 2 entries')).toBeVisible();

      // Click add to bulk edit
      await casePage.dashboardLoc.buttonByText("Bulk Edit").click();
      await expect(casePage.dashboardLoc.common.pTextContainsAll("Showing 2 cases from Page 1")).toBeVisible();

      // Click checkbox select all
      await casePage.waitForSecond(2);
      await casePage.dashboardLoc.bulkEdit.checkBoxCheckAll.click();
      await expect(casePage.dashboardLoc.common.spanTextContainsAll("You have selected 2 cases")).toBeVisible();

      //Verify UI in step 2
      await casePage.dashboardLoc.buttonByText("Next").click();
      await expect(casePage.page.locator('#root')).toMatchAriaSnapshot(`
        - text: "2 of 4 steps Step 1: Choose Cases Step 2: Apply Bulk Action Step 3: Action Detail Step 4: Confirmation"
        - paragraph:
          - text: "Step 2: Apply Bulk Action"
          - img
        - paragraph: Choose the action you want to apply to the selected cases.
        - radio "Change status detail"
        - text: Change status detail Update the values of the status details.
        - radio "Modify tag"
        - text: Modify tag Add to existing, Replace all, or Remove existing tag.
        - radio "Change category"
        - text: Change category Selecting personal injury category.
        - radio "Change law firm"
        - text: Change law firm Selecting new firm for case representation.
        - radio "Change counsel"
        - text: Change counsel Selecting new representation.
        - radio "Change case manager"
        - text: Change case manager Selecting new legal case manager.
        - radio "Add note"
        - text: Add note Add a note to this case. You'll find it in the Team Discussion Room.
        - radio "Assignee/Unassigned"
        - text: Assignee/Unassigned Designates the person responsible for completing or following up on the selected cases.
        - radio "Read/Unread"
        - text: Read/Unread Mark as Read or Unread.
        - radio "Active/Reference"
        - text: Active/Reference Move to the Active workspace for high visibility or the Reference section for low visibility.
        - button "Back"
        - button "Next" [disabled]
        `);

      // Verify choose Active/Reference action
      await casePage.dashboardLoc.bulkEdit.inputBulkEditAction("Active/Reference").check();
      await expect(casePage.dashboardLoc.buttonByText("Next")).toBeEnabled();
      await casePage.dashboardLoc.buttonByText("Next").click();

      // Verify choose Reference in step 3
      await casePage.dashboardLoc.bulkEdit.inputBulkEditAction("Reference").check();
      await expect(casePage.dashboardLoc.buttonByText("Next")).toBeEnabled();
      await casePage.dashboardLoc.buttonByText("Next").click();
      await casePage.dashboardLoc.buttonByText("Confirmation").click();
    });

    await test.step("Verify cases after bulk edit", async () => {
      await casePage.open();
      // Verify search in tab Active
      await casePage.dashboardLoc.table.tabInTable("Active").click();
      await casePage.search(fullName);
      await casePage.waitAllRequestCompeleted();
      await expect(casePage.dashboardLoc.table.itemInRow(caseId1)).not.toBeVisible();
      await expect(casePage.dashboardLoc.table.itemInRow(caseId2)).not.toBeVisible();

      // Verify search in tab Reference
      await casePage.dashboardLoc.table.tabInTable("Reference").click();
      await casePage.search(fullName);
      await casePage.waitAllRequestCompeleted();
      await expect(casePage.dashboardLoc.table.itemInRow(caseId1)).toBeVisible();
      await expect(casePage.dashboardLoc.table.itemInRow(caseId2)).toBeVisible();
    });

    await test.step("Verify change 2 cases to active", async () => {
      // Click add to bulk edit
      await casePage.dashboardLoc.buttonByText("Bulk Edit").click();
      await expect(casePage.dashboardLoc.common.pTextContainsAll("Showing 2 cases from Page 1")).toBeVisible();

      // Click checkbox select all
      await casePage.waitForSecond(2);
      await casePage.dashboardLoc.bulkEdit.checkBoxCheckAll.click();
      await expect(casePage.dashboardLoc.common.spanTextContainsAll("You have selected 2 cases")).toBeVisible();

      // Verify choose Active/Reference action
      await casePage.dashboardLoc.buttonByText("Next").click();
      await casePage.dashboardLoc.bulkEdit.inputBulkEditAction("Active/Reference").check();
      await expect(casePage.dashboardLoc.buttonByText("Next")).toBeEnabled();
      await casePage.dashboardLoc.buttonByText("Next").click();

      // Verify choose Reference in step 3
      await casePage.dashboardLoc.bulkEdit.inputBulkEditAction("Active").check();
      await expect(casePage.dashboardLoc.buttonByText("Next")).toBeEnabled();
      await casePage.dashboardLoc.buttonByText("Next").click();
      await casePage.dashboardLoc.buttonByText("Confirmation").click();
    });

    await test.step("Verify cases after bulk edit", async () => {
      await casePage.open();
      // Verify search in tab Active
      await casePage.dashboardLoc.table.tabInTable("Active").click();
      await casePage.search(fullName);
      await casePage.waitAllRequestCompeleted();
      await expect(casePage.dashboardLoc.table.itemInRow(caseId1)).toBeVisible();
      await expect(casePage.dashboardLoc.table.itemInRow(caseId2)).toBeVisible();

      // Verify search in tab Reference
      await casePage.dashboardLoc.table.tabInTable("Reference").click();
      await casePage.search(fullName);
      await casePage.waitAllRequestCompeleted();
      await expect(casePage.dashboardLoc.table.itemInRow(caseId1)).not.toBeVisible();
      await expect(casePage.dashboardLoc.table.itemInRow(caseId2)).not.toBeVisible();
    });

    await test.step("Teardown - Archive cases", async () => {
      await apiHelper.archiveCase(caseId1);
      await apiHelper.archiveCase(caseId2);
      await apiHelper.archiveCustomer(customerId);
    });
  });

  test("CASE_036 - Verify bulk edit function to change read/unread", {
    tag: ['@CASE_036', '@case', '@function']
  }, async ({ conf, apiHelper }) => {
    let customerId: string;
    let caseId1: string;
    let caseId2: string;
    const doiCase1 = await randomDate();
    const doiCase2 = await randomDate();
    const dob = await randomDate();
    const firstName = `${randomText(5)}${randomString(5)}`;
    const lastName = `${randomText(5)}${randomString(5)}`;
    const capitalize = (str: string) => str.charAt(0).toUpperCase() + str.slice(1);
    const fullName = `${capitalize(firstName)} ${capitalize(lastName)}`;

    await test.step("Precondition: Create 1 client and 2 cases with same client", async () => {
      // Create customer first
      const customerResult = await apiHelper.createCustomer({
        first_name: firstName,
        last_name: lastName,
        birthday: dob
      });
      customerId = customerResult.customer_id;

      // Create case 1 with the customer
      const case1Result = await apiHelper.createCase({
        customer_id: customerId,
        date_of_injury: doiCase1,
        category_id: conf.data.category_id
      });
      caseId1 = case1Result.case_id;

      // Create case 2 with the same customer
      const case2Result = await apiHelper.createCase({
        customer_id: customerId,
        date_of_injury: doiCase2,
        category_id: conf.data.category_id
      });
      caseId2 = case2Result.case_id;
    });

    await test.step("Verify change 2 cases to unread", async () => {
      // Search 2 cases
      await casePage.reload();
      await casePage.dashboardLoc.table.tabInTable("Active").click();

      await casePage.search(fullName);
      await expect(casePage.dashboardLoc.table.itemInRow(caseId1)).toBeVisible();
      await expect(casePage.dashboardLoc.table.itemInRow(caseId2)).toBeVisible();
      await expect(casePage.dashboardLoc.common.pTextContainsAll('Showing 1 to 2 of 2 entries')).toBeVisible();

      // Reset column and verify UI
      await casePage.resetToDefaultColumn(casePage.caseProps.customizedColumns, 1);
      await verifyScreenshot("cases-unread-before-bulk-edit.png", casePage.dashboardLoc.table.container, [
        casePage.dashboardLoc.table.itemInRow(caseId1),
        casePage.dashboardLoc.table.itemInRow(caseId2),
        casePage.dashboardLoc.table.itemInRow(fullName),
        casePage.dashboardLoc.table.itemInRow2(fullName),
        casePage.dashboardLoc.table.itemInRow(doiCase1),
        casePage.dashboardLoc.table.itemInRow(doiCase2)
      ], 0.02);

      // Click add to bulk edit
      await casePage.dashboardLoc.buttonByText("Bulk Edit").click();
      await expect(casePage.dashboardLoc.common.pTextContainsAll("Showing 2 cases from Page 1")).toBeVisible();

      // Click checkbox select all
      await casePage.waitForSecond(2);
      await casePage.dashboardLoc.bulkEdit.checkBoxCheckAll.click();
      await expect(casePage.dashboardLoc.common.spanTextContainsAll("You have selected 2 cases")).toBeVisible();

      await casePage.dashboardLoc.buttonByText("Next").click();

      // Verify choose Read/Unread action
      await casePage.dashboardLoc.bulkEdit.inputBulkEditAction("Read/Unread").check();
      await expect(casePage.dashboardLoc.buttonByText("Next")).toBeEnabled();
      await casePage.dashboardLoc.buttonByText("Next").click();

      // Verify choose Read in step 3
      await casePage.dashboardLoc.bulkEdit.inputBulkEditAction("Read").check();
      await expect(casePage.dashboardLoc.buttonByText("Next")).toBeEnabled();
      await casePage.dashboardLoc.buttonByText("Next").click();
      await casePage.dashboardLoc.buttonByText("Confirmation").click();
    });

    await test.step("Verify cases after bulk edit", async () => {
      await casePage.open();
      // Verify search in tab Active
      await casePage.dashboardLoc.table.tabInTable("Active").click();
      await casePage.search(fullName);
      await casePage.waitAllRequestCompeleted();
      await casePage.resetToDefaultColumn(casePage.caseProps.customizedColumns, 1);
      await verifyScreenshot("cases-unread-after-bulk-edit.png", casePage.dashboardLoc.table.container, [
        casePage.dashboardLoc.table.itemInRow(caseId1),
        casePage.dashboardLoc.table.itemInRow(caseId2),
        casePage.dashboardLoc.table.itemInRow(fullName),
        casePage.dashboardLoc.table.itemInRow2(fullName),
        casePage.dashboardLoc.table.itemInRow(doiCase1),
        casePage.dashboardLoc.table.itemInRow(doiCase2)
      ], 0.02);
    });

    await test.step("Verify change 2 cases to unread", async () => {
      // Click add to bulk edit
      await casePage.dashboardLoc.buttonByText("Bulk Edit").click();
      await expect(casePage.dashboardLoc.common.pTextContainsAll("Showing 2 cases from Page 1")).toBeVisible();

      // Click checkbox select all
      await casePage.waitForSecond(2);
      await casePage.dashboardLoc.bulkEdit.checkBoxCheckAll.click();
      await expect(casePage.dashboardLoc.common.spanTextContainsAll("You have selected 2 cases")).toBeVisible();

      // Verify choose Read/Unread action
      await casePage.dashboardLoc.buttonByText("Next").click();
      await casePage.dashboardLoc.bulkEdit.inputBulkEditAction("Read/Unread").check();
      await expect(casePage.dashboardLoc.buttonByText("Next")).toBeEnabled();
      await casePage.dashboardLoc.buttonByText("Next").click();

      // Verify choose Unread in step 3
      await casePage.dashboardLoc.bulkEdit.inputBulkEditAction("Unread").check();
      await expect(casePage.dashboardLoc.buttonByText("Next")).toBeEnabled();
      await casePage.dashboardLoc.buttonByText("Next").click();
      await casePage.dashboardLoc.buttonByText("Confirmation").click();
    });

    await test.step("Verify cases after bulk edit", async () => {
      await casePage.open();
      // Verify search in tab Active
      await casePage.dashboardLoc.table.tabInTable("Active").click();
      await casePage.search(fullName);
      await casePage.waitAllRequestCompeleted();
      await casePage.resetToDefaultColumn(casePage.caseProps.customizedColumns, 1);
      await verifyScreenshot("cases-unread-before-bulk-edit.png", casePage.dashboardLoc.table.container, [
        casePage.dashboardLoc.table.itemInRow(caseId1),
        casePage.dashboardLoc.table.itemInRow(caseId2),
        casePage.dashboardLoc.table.itemInRow(fullName),
        casePage.dashboardLoc.table.itemInRow2(fullName),
        casePage.dashboardLoc.table.itemInRow(doiCase1),
        casePage.dashboardLoc.table.itemInRow(doiCase2)
      ], 0.02);
    });

    await test.step("Teardown - Archive cases", async () => {
      await apiHelper.archiveCase(caseId1);
      await apiHelper.archiveCase(caseId2);
      await apiHelper.archiveCustomer(customerId);
    });
  });

  // Attachment 

  test("CASE_038 - Verify Remove file", {
    tag: ['@CASE_038', '@case', '@function', '@attachment']
  }, async ({ conf, apiHelper }) => {
    const doi = await randomDate();
    const dob = await randomDate();
    const firstName = `${randomText(5)}${randomString(5)}`;
    const lastName = `${randomText(5)}${randomString(5)}`;
    let customerId: string;
    let caseId1: string;

    await test.step("Preconditon: Create new case", async () => {
      const customerResult = await apiHelper.createCustomer({
        first_name: firstName,
        last_name: lastName,
        birthday: dob
      });
      customerId = customerResult.customer_id;

      // Create case 1 with the customer
      const caseResult = await apiHelper.createCase({
        customer_id: customerId,
        date_of_injury: doi,
        category_id: conf.data.category_id
      });
      caseId1 = caseResult.case_id;
    });

    await test.step("Goto case and upload 2 files", async () => {
      await casePage.open();
      await casePage.getDetailCase(caseId1);
      await casePage.dashboardLoc.detail.tabName("Attachment").click();
      const filePathValidPdf = path.resolve(__dirname, `test-files/file-pdf.pdf`);
      const filePathValidJpg = path.resolve(__dirname, `test-files/file-jpg.jpg`);
      await casePage.waitForSecond(1);

      await casePage.caseLoc.detail.inputUploadfile.setInputFiles([filePathValidPdf, filePathValidJpg]);
      await expect(casePage.dashboardLoc.common.divText("file-pdf.pdf")).toBeVisible();
      await expect(casePage.dashboardLoc.common.divText("file-jpg.jpg")).toBeVisible();
    });

    await test.step("Verify remove file in list view", async () => {
      await casePage.switchToAttachmentLayout('list');
      await casePage.dashboardLoc.detail.fileAttachmentRow("file-pdf.pdf").hover();
      await expect(casePage.dashboardLoc.detail.iconRemoveFile("file-pdf.pdf")).toBeVisible();
      await casePage.dashboardLoc.detail.iconRemoveFile("file-pdf.pdf").click();

      // Show modal confirm
      await expect(casePage.dashboardLoc.modal.headerModalh2("Remove this file?")).toBeVisible();
      await casePage.dashboardLoc.modal.inputByID("input_text-remove").fill("Remove");
      await expect(casePage.dashboardLoc.buttonByText("Remove")).toBeEnabled();
      await casePage.dashboardLoc.buttonByText("Remove").click();
      await expect(casePage.dashboardLoc.msgRemoveAttachment).toBeVisible();
      await casePage.dashboardLoc.btnClosePopupNotification.click();
      await expect(casePage.dashboardLoc.common.divText("file-pdf.pdf")).not.toBeVisible();
    });

    await test.step("Verify remove file in grid view", async () => {
      await casePage.switchToAttachmentLayout('grid');
      await casePage.dashboardLoc.detail.buttonDotsAction.first().click();
      await casePage.dashboardLoc.common.divText("Remove").click();

      // Show modal confirm
      await expect(casePage.dashboardLoc.modal.headerModalh2("Remove this file?")).toBeVisible();
      await casePage.dashboardLoc.modal.inputByID("input_text-remove").fill("Remove");
      await expect(casePage.dashboardLoc.buttonByText("Remove")).toBeEnabled();
      await casePage.dashboardLoc.buttonByText("Remove").click();
      await expect(casePage.dashboardLoc.msgRemoveAttachment).toBeVisible();
      await expect(casePage.dashboardLoc.common.divText("file-jpg.jpg")).not.toBeVisible();
    });

    await test.step("Teardown - Archive case and customer", async () => {
      await apiHelper.archiveCase(caseId1);
      await apiHelper.archiveCustomer(customerId);
    });
  });

  test("CASE_039 - Verify download file", {
    tag: ['@CASE_038', '@case', '@function', '@attachment']
  }, async ({ conf, apiHelper }) => {
    const doi = await randomDate();
    const dob = await randomDate();
    const firstName = `${randomText(5)}${randomString(5)}`;
    const lastName = `${randomText(5)}${randomString(5)}`;
    let customerId: string;
    let caseId1: string;

    await test.step("Preconditon: Create new case", async () => {
      const customerResult = await apiHelper.createCustomer({
        first_name: firstName,
        last_name: lastName,
        birthday: dob
      });
      customerId = customerResult.customer_id;

      // Create case 1 with the customer
      const caseResult = await apiHelper.createCase({
        customer_id: customerId,
        date_of_injury: doi,
        category_id: conf.data.category_id
      });
      caseId1 = caseResult.case_id;
    });

    await test.step("Goto case and upload 2 files", async () => {
      await casePage.open();
      await casePage.getDetailCase(caseId1);
      await casePage.dashboardLoc.detail.tabName("Attachment").click();
      const filePathValidPdf = path.resolve(__dirname, `test-files/file-pdf.pdf`);
      await casePage.caseLoc.detail.inputUploadfile.setInputFiles([filePathValidPdf]);
      await expect(casePage.dashboardLoc.common.divText("file-pdf.pdf")).toBeVisible();
    });

    await test.step("Verify download file in list view", async () => {
      await casePage.switchToAttachmentLayout('list');
      await casePage.dashboardLoc.detail.fileAttachmentRow("file-pdf.pdf").hover();
      await expect(casePage.dashboardLoc.detail.iconDownloadFile("file-pdf.pdf")).toBeVisible();

      const downloadPromise = casePage.page.waitForEvent('download');
      await casePage.dashboardLoc.detail.iconDownloadFile("file-pdf.pdf").click();
      const download = await downloadPromise;

      const fileName = download.suggestedFilename();
      expect(fileName).toContain('file-pdf');

      const savePath = `test-results/${fileName}`;
      await download.saveAs(savePath);

      const fileContent = require('fs').readFileSync(savePath);
      expect(fileContent.length).toBeGreaterThan(0);

      require('fs').unlinkSync(savePath);
    });

    await test.step("Verify download file in grid view", async () => {
      await casePage.switchToAttachmentLayout('grid');
      await casePage.dashboardLoc.detail.buttonDotsAction.first().click();
      await expect(casePage.dashboardLoc.common.aText("Download")).toBeVisible();
      const downloadPromise = casePage.page.waitForEvent('download');
      await casePage.dashboardLoc.common.aText("Download").click();
      const download = await downloadPromise;

      const fileName = download.suggestedFilename();
      expect(fileName).toContain('file-pdf');

      const savePath = `test-results/${fileName}`;
      await download.saveAs(savePath);

      const fileContent = require('fs').readFileSync(savePath);
      expect(fileContent.length).toBeGreaterThan(0);

      require('fs').unlinkSync(savePath);
    });

    await test.step("Teardown - Archive case and customer", async () => {
      await apiHelper.archiveCase(caseId1);
      await apiHelper.archiveCustomer(customerId);
    });
  });

  test("CASE_040 - Verify Edit file name", {
    tag: ['@CASE_040', '@case', '@function', '@attachment']
  }, async ({ conf, apiHelper }) => {
    const doi = await randomDate();
    const dob = await randomDate();
    const firstName = `${randomText(5)}${randomString(5)}`;
    const lastName = `${randomText(5)}${randomString(5)}`;
    let customerId: string;
    let caseId1: string;
    let newFileName: string = "file-pdf-renamed";
    await test.step("Preconditon: Create new case", async () => {
      const customerResult = await apiHelper.createCustomer({
        first_name: firstName,
        last_name: lastName,
        birthday: dob
      });
      customerId = customerResult.customer_id;

      // Create case 1 with the customer
      const caseResult = await apiHelper.createCase({
        customer_id: customerId,
        date_of_injury: doi,
        category_id: conf.data.category_id
      });
      caseId1 = caseResult.case_id;
    });

    await test.step("Goto case and upload 2 files", async () => {
      await casePage.open();
      await casePage.getDetailCase(caseId1);
      await casePage.dashboardLoc.detail.tabName("Attachment").click();
      const filePathValidPdf = path.resolve(__dirname, `test-files/file-pdf.pdf`);
      await casePage.caseLoc.detail.inputUploadfile.setInputFiles([filePathValidPdf]);
      await expect(casePage.dashboardLoc.common.divText("file-pdf.pdf")).toBeVisible();
    });

    await test.step("Verify edit file name in list view", async () => {
      await casePage.switchToAttachmentLayout('list');
      await casePage.dashboardLoc.detail.fileAttachmentRow("file-pdf.pdf").hover();
      await expect(casePage.dashboardLoc.detail.iconEditFileName("file-pdf.pdf")).toBeVisible();
      await casePage.dashboardLoc.detail.iconEditFileName("file-pdf.pdf").click();

      // Verify empty file name not allow to submit
      await casePage.dashboardLoc.modal.inputByID("input_edit-file-name").clear();
      await casePage.dashboardLoc.detail.buttonActionEdit.nth(1).click();
      await expect(casePage.dashboardLoc.common.spanText(conf.data.error_empty)).toBeVisible();

      // Verify edit to long file name
      await casePage.dashboardLoc.modal.inputByID("input_edit-file-name").fill(conf.data.name_long);
      await casePage.dashboardLoc.detail.buttonActionEdit.nth(1).click();
      await expect(casePage.dashboardLoc.common.spanText(conf.data.error_long)).toBeVisible();

      // Verify edit file name successfully

      await casePage.dashboardLoc.modal.inputByID("input_edit-file-name").fill(newFileName);
      await casePage.dashboardLoc.detail.buttonActionEdit.nth(1).click();
      await expect(casePage.dashboardLoc.msgChangeNameAttachment).toBeVisible();
      await expect(casePage.dashboardLoc.common.divText(newFileName)).toBeVisible();
    });

    await test.step("Verify edit file name in grid view", async () => {
      await casePage.switchToAttachmentLayout('grid');
      await casePage.dashboardLoc.detail.fileAttachmentGrid(newFileName).hover();
      await expect(casePage.dashboardLoc.detail.iconEditFileNameGrid(newFileName)).toBeVisible();
      await casePage.dashboardLoc.detail.iconEditFileNameGrid(newFileName).click();
      await expect(casePage.dashboardLoc.modal.headerModalh2("Rename")).toBeVisible();

      // Verify empty file name not allow to submit
      await casePage.dashboardLoc.modal.inputByID("input_edit-file-name").clear();
      await casePage.dashboardLoc.buttonByText("Ok").click();
      await expect(casePage.dashboardLoc.common.spanText(conf.data.error_empty)).toBeVisible();

      // Verify edit to long file name
      await casePage.dashboardLoc.modal.inputByID("input_edit-file-name").fill(conf.data.name_long);
      await casePage.dashboardLoc.buttonByText("Ok").click();
      await expect(casePage.dashboardLoc.common.spanText(conf.data.error_long)).toBeVisible();

      // Verify edit file name successfully
      await casePage.dashboardLoc.modal.inputByID("input_edit-file-name").fill(newFileName);
      await casePage.dashboardLoc.buttonByText("Ok").click();
      await expect(casePage.dashboardLoc.msgChangeNameAttachment).toBeVisible();
      await expect(casePage.dashboardLoc.common.divText(newFileName)).toBeVisible();
    });

    await test.step("Teardown - Archive case and customer", async () => {
      await apiHelper.archiveCase(caseId1);
      await apiHelper.archiveCustomer(customerId);
    });
  });

  test("CASE_041 - Verify upload single file", {
    tag: ['@CASE_041', '@case', '@function', '@attachment']
  }, async ({ conf, apiHelper }) => {
    const doi = await randomDate();
    const dob = await randomDate();
    const firstName = `${randomText(5)}${randomString(5)}`;
    const lastName = `${randomText(5)}${randomString(5)}`;
    let customerId: string;
    let caseId1: string;
    const filePathValidPdf = path.resolve(__dirname, `test-files/file-pdf.pdf`);
    const filePath25mb = path.resolve(__dirname, `test-files/file-25mb.png`);
    const filePathInvalid = path.resolve(__dirname, `test-files/file-json.json`);

    await test.step("Preconditon: Create new case", async () => {
      const customerResult = await apiHelper.createCustomer({
        first_name: firstName,
        last_name: lastName,
        birthday: dob
      });
      customerId = customerResult.customer_id;

      // Create case 1 with the customer
      const caseResult = await apiHelper.createCase({
        customer_id: customerId,
        date_of_injury: doi,
        category_id: conf.data.category_id
      });
      caseId1 = caseResult.case_id;
    });

    await test.step("Goto case and upload file > 25mb", async () => {
      await casePage.open();
      await casePage.getDetailCase(caseId1);
      await casePage.dashboardLoc.detail.tabName("Attachment").click();

      await casePage.caseLoc.detail.inputUploadfile.setInputFiles([filePath25mb]);
      await expect(casePage.dashboardLoc.common.spanText(conf.data.error_25mb)).toBeVisible();
      await expect(casePage.dashboardLoc.common.spanText(`0 upload complete`)).toBeVisible();
    });

    await test.step("Verify upload more than 50 files", async () => {
      const filesArray = Array(51).fill(filePathValidPdf);
      await casePage.caseLoc.detail.inputUploadfile.setInputFiles(filesArray);
      await expect(casePage.dashboardLoc.modal.headerModalh2("Warning").first()).toBeVisible();
      await expect(casePage.dashboardLoc.common.pTextContainsAll(conf.data.error_upload_maximum_file)).toBeVisible();
      await casePage.dashboardLoc.detail.btnCloseModalWarning(1).click();
      await expect(casePage.dashboardLoc.modal.headerModalh2("Warning").first()).not.toBeVisible();
    });

    await test.step("Verify upload invalid file type", async () => {
      await casePage.caseLoc.detail.inputUploadfile.setInputFiles(filePathInvalid);
      await expect(casePage.dashboardLoc.modal.headerModalh2("Warning").nth(1)).toBeVisible();
      await expect(casePage.dashboardLoc.common.pText(conf.data.error_invalid)).toBeVisible();
      await casePage.dashboardLoc.detail.btnCloseModalWarning(2).click();
      await expect(casePage.dashboardLoc.modal.headerModalh2("Warning").nth(1)).not.toBeVisible();
    });

    await test.step("Verify upload file 2 times and replace file", async () => {
      // Upload file first time
      await casePage.caseLoc.detail.inputUploadfile.setInputFiles(filePathValidPdf);
      await expect(casePage.dashboardLoc.common.divText("file-pdf.pdf")).toBeVisible();
      await expect(casePage.dashboardLoc.common.spanText(`1 upload complete`)).toBeVisible();

      // Upload file second time with same name but different content
      await casePage.caseLoc.detail.inputUploadfile.setInputFiles(filePathValidPdf);
      await expect(casePage.dashboardLoc.common.divText("file-pdf (1).pdf")).toBeVisible();
      await expect(casePage.dashboardLoc.common.spanText(`2 uploads complete`)).toBeVisible();
    });

    await test.step("Teardown - Archive case and customer", async () => {
      await apiHelper.archiveCase(caseId1);
      await apiHelper.archiveCustomer(customerId);
    });
  });

  test("CASE_042 - Verify upload multiple files", {
    tag: ['@CASE_042', '@case', '@function', '@attachment']
  }, async ({ conf, apiHelper }) => {
    const doi = await randomDate();
    const dob = await randomDate();
    const firstName = `${randomText(5)}${randomString(5)}`;
    const lastName = `${randomText(5)}${randomString(5)}`;
    let customerId: string;
    let caseId1: string;
    const filePathValidWord = path.resolve(__dirname, `test-files/file-doc.doc`);
    const filePathValidExcel = path.resolve(__dirname, `test-files/file-xls.xls`);
    const filePathValidPng = path.resolve(__dirname, `test-files/file-png.png`);
    const filePath25mb = path.resolve(__dirname, `test-files/file-25mb.png`);
    const filePathInvalid = path.resolve(__dirname, `test-files/file-json.json`);

    await test.step("Preconditon: Create new case", async () => {
      const customerResult = await apiHelper.createCustomer({
        first_name: firstName,
        last_name: lastName,
        birthday: dob
      });
      customerId = customerResult.customer_id;

      // Create case 1 with the customer
      const caseResult = await apiHelper.createCase({
        customer_id: customerId,
        date_of_injury: doi,
        category_id: conf.data.category_id
      });
      caseId1 = caseResult.case_id;
    });

    await test.step("Goto case and upload multiples file", async () => {
      await casePage.open();
      await casePage.getDetailCase(caseId1);
      await casePage.dashboardLoc.detail.tabName("Attachment").click();

      await casePage.caseLoc.detail.inputUploadfile.setInputFiles([filePath25mb, filePathInvalid, filePathValidWord, filePathValidExcel, filePathValidPng]);

      // Show modal warning for invalid file type
      await expect(casePage.dashboardLoc.modal.headerModalh2("Warning").nth(1)).toBeVisible();
      await expect(casePage.dashboardLoc.common.pText(conf.data.error_invalid)).toBeVisible();
      await casePage.dashboardLoc.buttonByText("Skip Files").click();
      await expect(casePage.dashboardLoc.modal.headerModalh2("Warning").nth(1)).not.toBeVisible();

      await expect(casePage.dashboardLoc.common.spanText(`3 uploads complete`)).toBeVisible();

      // Show error message for file > 25mb
      await expect(casePage.dashboardLoc.common.spanText(conf.data.error_25mb)).toBeVisible();

      // Show only 3 valid files in attachment list
      await expect(casePage.dashboardLoc.common.divText("file-doc.doc")).toBeVisible();
      await expect(casePage.dashboardLoc.common.divText("file-xls.xls")).toBeVisible();
      await expect(casePage.dashboardLoc.common.divText("file-png.png")).toBeVisible();
    });

    await test.step("Teardown - Archive case and customer", async () => {
      await apiHelper.archiveCase(caseId1);
      await apiHelper.archiveCustomer(customerId);
    });
  })
});

test.describe("Case already exists", async () => {
  let loginPage: LoginPage;
  let casePage: CasePage;

  test.beforeEach("Login and verify data", async ({ page, conf }) => {
    loginPage = new LoginPage(page);
    casePage = new CasePage(page);

    await test.step("Login and go to case page", async () => {
      await loginPage.open();
      await loginPage.login(conf.data.username, conf.data.password);
      await expect(loginPage.baseLoc.dashboardContainer).toBeVisible();
      await casePage.open();
    })

    await test.step("Search with exist case", async () => {
      if (conf.data.only_search) {
        return casePage.search(conf.data.case);
      }

      await casePage.getDetailCase(conf.data.case);
      await casePage.waitForSecond(2);

      if (conf.data.not_update) {
        return;
      }
      await expect(casePage.caseLoc.detail.buttonUpdateCase).toBeVisible();
      await casePage.caseLoc.detail.buttonUpdateCase.click({ force: true });
      await expect(casePage.dashboardLoc.modal.headerModal("Case Detail")).toBeVisible();
    })

    //Bổ sung thêm check info detail và info modal update (sau sẽ có thêm api -> bổ sung sau)
  });

  test("CASE_014 - Verify update case", {
    tag: ['@CASE_014', '@case', '@function']
  }, async ({ conf }) => {
    test.setTimeout(180_000);

    await test.step("Verify click cancel without change data", async () => {
      await casePage.caseLoc.detail.btnCloseModalUpdate.click();
      await expect(casePage.dashboardLoc.modal.headerModal("Case Detail")).not.toBeVisible();

      // Reopen update modal
      await casePage.caseLoc.detail.buttonUpdateCase.click({ force: true });
      await expect(casePage.dashboardLoc.modal.headerModal("Case Detail")).toBeVisible();
    });

    await test.step("Fill data to update modal", async () => {
      for (const formField of casePage.caseUpdateForm) {
        const fieldLocator = casePage.caseLoc.detail.update.fieldForm(formField.type, formField.inputName);
        await fieldLocator.fill(conf.data.update[formField.inputName]);
        await expect(fieldLocator).toHaveValue(conf.data.update[formField.inputName]);
      }
    });

    await test.step("Verify click cancel with change data", async () => {
      await casePage.caseLoc.detail.btnCloseModalUpdate.click();
      await expect(casePage.dashboardLoc.buttonByText("Back")).toBeVisible();
      await casePage.dashboardLoc.buttonByText("Back").click();
    });

    await test.step("Click update and verify data", async () => {
      await casePage.waitForSecond(2);
      await casePage.dashboardLoc.modal.headerModal("Case Detail").click();
      await casePage.dashboardLoc.buttonByText("Update").first().click({ force: true });
      await expect(casePage.caseLoc.detail.addLegalModal.msgSuccess.first()).toBeVisible();
      await expect(casePage.dashboardLoc.modal.headerModal("Case Detail")).not.toBeVisible();
    })

    await test.step("Teardown data", async () => {
      await casePage.caseLoc.detail.buttonUpdateCase.click();
      await expect(casePage.dashboardLoc.modal.headerModal("Case Detail")).toBeVisible();

      // Clear all form fields
      for (const formField of casePage.caseUpdateForm) {
        await casePage.caseLoc.detail.update.fieldForm(formField.type, formField.inputName).clear();
      }

      await casePage.dashboardLoc.buttonByText("Update").first().click();
      await expect(casePage.caseLoc.detail.addLegalModal.msgSuccess.first()).toBeVisible();
    });
  })

  // test("CASE_015 - Verify update case when clear Law Firm, Counsel and Case Manager", {
  //   tag: ['@CASE_015', '@case', '@function']
  // }, async ({ conf }) => {
  //   test.setTimeout(150_000)
  //   await test.step("Clear Law Firm, Counsel and Case Manager and submit", async () => {
  //     await casePage.caseLoc.detail.update.selectLawFirm("autocomplete_law_firm_id").first().click();
  //     await casePage.caseLoc.detail.update.selectLawFirm("autocomplete_lawyer_id").first().click();
  //     await casePage.caseLoc.detail.update.selectLawFirm("autocomplete_case_manager_id").first().click();
  //     await casePage.dashboardLoc.buttonByText("Update").first().click();

  //     await expect(casePage.caseLoc.detail.addLegalModal.msgSuccess.first()).toBeVisible();
  //     await expect(casePage.dashboardLoc.modal.headerModal("Case Detail")).not.toBeVisible();
  //     await expect(casePage.caseLoc.detail.noLegal).toBeVisible();
  //   })

  //   await test.step("Teardown data", async () => {
  //     await casePage.fillLegalContact(conf.data.business, conf.data.user_recive_case);
  //     await casePage.caseLoc.detail.btnSubmitLegalContact.click();
  //     await expect(casePage.caseLoc.detail.addLegalModal.msgSuccess.first()).toBeVisible();
  //     await expect(casePage.caseLoc.detail.noLegal).not.toBeVisible();
  //   })
  // })

  test("CASE_016 - Verify when archived/unArchived case has no request yet", {
    tag: ['@CASE_016', '@case', '@function']
  }, async ({ conf, casePage16 }) => {
    test.setTimeout(150_000);
    await test.step("Verify when archive case", async () => {
      await expect(casePage16.caseLoc.detail.buttonUpdateCase).toBeVisible();
      await casePage16.caseLoc.detail.buttonUpdateCase.click({ force: true });
      await casePage16.dashboardLoc.buttonByText("Archive").first().click();
      await expect(casePage16.caseLoc.detail.update.msgArchive).toBeVisible();
      await casePage.dashboardLoc.btnClosePopupNotification.click();

      await expect(casePage16.dashboardLoc.modal.headerModalh2("Case Detail")).not.toBeVisible();
      await expect(casePage16.caseLoc.detail.update.boxHeaderArchive).toBeVisible();
      await casePage16.page.reload();// Sau khi client update tự reload cần bỏ

      // Verify activity
      const newestActivity = await casePage16.getNewestActivity();
      expect(newestActivity).toContain(`archive case ${await getTodayInTimeZone()}`);

      //Verify not show in table
      await casePage16.open();
      await casePage16.dashboardLoc.search.inputSearch.fill(conf.data.case);
      await expect(casePage16.caseLoc.msgNoResultFound).toBeVisible();
    })

    await test.step("Verify when unArchive case", async () => {
      //Verify data show in archived table
      await casePage16.dashboardLoc.search.filter.btn.click();
      await casePage16.caseLoc.inputArchive.fill("Yes");
      await casePage16.caseLoc.boxSelectArchive("Yes").click();
      await casePage16.dashboardLoc.search.filter.popup.btnApply.click();
      await expect(casePage16.dashboardLoc.table.itemInRow(conf.data.case)).toBeVisible();

      //Verify when unArchive case
      await casePage16.dashboardLoc.table.itemInRow(conf.data.case).click();
      await casePage16.caseLoc.detail.update.btnUnArchive.click();
      await expect(casePage16.caseLoc.detail.update.msgUnArchive.first()).toBeVisible();
      await expect(casePage16.caseLoc.detail.update.boxHeaderArchive).not.toBeVisible();
      await casePage16.page.reload(); // Sau khi client update tự reload cần bỏ

      // Verify change activity
      const newestActivity = await casePage16.getNewestActivity();
      expect(newestActivity).toContain(`unarchive case ${await getTodayInTimeZone()}`);

      //Verify case exist in table
      await casePage16.open();
      await casePage16.dashboardLoc.search.inputSearch.fill(conf.data.case);
      await expect(casePage16.dashboardLoc.table.itemInRow(conf.data.case)).toBeVisible();
    })
  })

  test("CASE_017 - Verify when archived/unArchived case has request and transfer to another case", {
    tag: ['@CASE_017', '@case', '@function']
  }, async ({ conf, casePage17 }) => {
    await test.step("Verify when archive case and transfer case", async () => {
      await expect(casePage17.dashboardLoc.buttonByText("Archive").first()).toBeVisible();
      await casePage17.dashboardLoc.buttonByText("Archive").first().click();

      await expect(casePage17.dashboardLoc.modal.headerModal("Archive")).toBeVisible();
      await casePage17.dashboardLoc.modal.inputByID("autocomplete_move_to_case_id").last().click();
      await casePage17.dashboardLoc.modal.inputByID("autocomplete_move_to_case_id").last().type(conf.data.case_transfer_to, { delay: 100 });
      await casePage17.caseLoc.detail.transfer.boxOption(conf.data.case_transfer_to).click();
      await casePage17.dashboardLoc.buttonByText("Archive").nth(1).click();
      await casePage17.dashboardLoc.btnClosePopupNotification.click();

      await expect(casePage17.caseLoc.detail.update.btnUnArchive).toBeVisible();

      // Verify activity 
      await casePage17.waitForSecond(3); // Load for update new activity
      const newestActivity = await casePage17.getNewestActivity();
      expect(newestActivity).toContain(`archive case and moved request Case: #${conf.data.case_transfer} #${conf.data.case_transfer_to}`);
    });

    await test.step("Verify when unarchive case", async () => {
      await casePage17.caseLoc.detail.update.btnUnArchive.click();
      await expect(casePage17.caseLoc.detail.update.msgUnArchive.first()).toBeVisible();
      await expect(casePage17.caseLoc.detail.update.boxHeaderArchive).not.toBeVisible();
    })

    await test.step("Verify case have request had transfered", async () => {
      await casePage17.open();
      await casePage17.getDetailCase(conf.data.case_transfer_to);
      await casePage17.dashboardLoc.detail.tabName("Summary/ Dive Deeper").click();
      await casePage17.waitForSecond(2);
      const requests = (await casePage17.caseLoc.detail.requestExist(conf.data.request_id_exist).all()).length;
      expect(requests).toBe(2);
    })

    await test.step("Transfer teardown data", async () => {
      //Transfer again to old case
      await casePage17.clickButtonDropdownSelect("BTN_SHOW_MOVE_REQUEST_OF_BUSINESS_MODAL");
      await expect(casePage17.dashboardLoc.modal.headerModal("Move Requests")).toBeVisible();
      await casePage17.caseLoc.detail.inputMoveRequest.click();
      await casePage17.caseLoc.detail.inputMoveRequest.type(conf.data.case_transfer, { delay: 100 });
      await casePage17.caseLoc.detail.transfer.boxOption(conf.data.case_transfer).click();
      await casePage17.caseLoc.buttonByText("Move").click();
    })
  })

  test("CASE_018 - Verify when archived/unArchived case has been requested and not transferred to another case", {
    tag: ['@CASE_018', '@case', '@function']
  }, async ({ conf, casePage18 }) => {
    test.setTimeout(180_000);
    let numberRequest: number;

    await test.step("Go to get number requests in dashboard", async () => {
      await casePage18.page.goto("")
      await expect(casePage18.dashboardLoc.common.pText("My Requests")).toBeVisible();
      await casePage18.dashboardLoc.common.pText("My Requests").click();

      await casePage18.dashboardLoc.detail.statusDetailsInput.nth(1).click();
      await expect(casePage18.dashboardLoc.common.spanText("Year to Date").last()).toBeVisible();
      await casePage18.dashboardLoc.common.spanText("Year to Date").last().click();

      await expect(casePage18.dashboardLoc.filterMonitor.requestTypeNumber.first()).toBeVisible();
      await casePage18.waitForSecond(2);
      const textRequest = await casePage18.dashboardLoc.filterMonitor.requestTypeNumber.first().innerText();
      numberRequest = parseInt(textRequest);
    });

    await test.step("Verify archive and not transferred to another case", async () => {
      // Get detail case
      await casePage18.open();
      await casePage18.getDetailCase(conf.data.case);
      await expect(casePage18.caseLoc.detail.buttonUpdateCase).toBeVisible();

      // Archive case
      await casePage18.caseLoc.detail.buttonUpdateCase.click({ force: true });
      await casePage.dashboardLoc.buttonByText("Archive").first().click();
      await expect(casePage18.dashboardLoc.modal.headerModal("Archive")).toBeVisible();

      await casePage18.caseLoc.detail.transfer.radioCheckArchive.click();
      await casePage.dashboardLoc.buttonByText("Archive").nth(1).click();
      await expect(casePage18.caseLoc.detail.transfer.msgArchive).toBeVisible();
      await casePage18.dashboardLoc.btnClosePopupNotification.click();
    });

    await test.step("Verify requests archive in table", async () => {
      await casePage18.page.reload();
      await expect(casePage18.caseLoc.detail.dataIntable("Archived Request", conf.data.request_id_exist)).toBeVisible();
      await expect(casePage18.caseLoc.detail.requestTableNoResult).toBeVisible();

      // unArchive case
      await casePage18.caseLoc.detail.update.btnUnArchive.click();
      await expect(casePage18.caseLoc.detail.update.msgUnArchive.first()).toBeVisible();
      await casePage18.dashboardLoc.btnClosePopupNotification.click();
    });

    await test.step("Verify requests change number in dashboard", async () => {
      await casePage18.page.goto("")
      await expect(casePage18.dashboardLoc.common.pText("My Requests")).toBeVisible();
      await casePage18.dashboardLoc.common.pText("My Requests").click();
      await casePage18.waitForSecond(2);
      const textRequestAfter = await casePage18.dashboardLoc.filterMonitor.requestTypeNumber.first().innerText();
      const numberRequestAfter = parseInt(textRequestAfter);
      expect(numberRequestAfter).toBe(numberRequest - 1);
    });

    await test.step("Verify requests back to request table", async () => {
      await casePage18.open();
      await casePage18.getDetailCase(conf.data.case);
      await expect(casePage18.caseLoc.detail.requestExist(conf.data.request_id_exist).first()).toBeVisible();
      await casePage18.waitForSecond(1);
      await casePage18.caseLoc.detail.requestExist(conf.data.request_id_exist).first().click({ force: true });
      await casePage18.caseLoc.detail.update.btnUnArchive.click();
      await casePage.dashboardLoc.buttonByText("Unarchive").click()
      await casePage.caseLoc.btnCloseModal.click();
      await casePage18.caseLoc.linkToCase(conf.data.case).first().click();
      await casePage18.waitForSecond(2);
      await expect(casePage18.caseLoc.detail.requestTableNoResult).not.toBeVisible();
    });

    await test.step("Verify requests number in dashboard back to initial", async () => {
      await casePage18.page.goto("");
      await expect(casePage18.dashboardLoc.common.pText("My Requests")).toBeVisible();
      await casePage18.dashboardLoc.common.pText("My Requests").click();
      await casePage18.waitForSecond(2);
      const textRequestFinal = await casePage18.dashboardLoc.filterMonitor.requestTypeNumber.first().innerText();
      const numberRequestFinal = parseInt(textRequestFinal);
      expect(numberRequestFinal).toBe(numberRequest);
    });
  });

  test("CASE_033 - Add and manage businesses in case's detail", {
    tag: ['@CASE_033', '@case', '@function']
  }, async ({ conf }) => {
    await test.step("Setup and verify initial business state", async () => {
      if (!await casePage.caseLoc.detail.singleBusinesses(conf.data.business_no_request_1).isVisible({ timeout: 3_000 })) {
        await casePage.addBusinessInDetail(conf.data.business_no_request_1);
      }
    });

    await test.step("Verify business actions based on request status", async () => {
      // Verify business with requests
      await casePage.caseLoc.detail.btnDropDownActionBySingleBusiness(conf.data.business_had_request).click();
      await expect(casePage.caseLoc.detail.btnDropdownBusiness).toBeVisible();
      await casePage.caseLoc.detail.btnDropdownBusiness.click();
      await expect(casePage.dashboardLoc.root).toMatchAriaSnapshot(`- text: Archive Move Requests`);

      // Verify business without requests
      await casePage.caseLoc.detail.btnDropDownActionBySingleBusiness(conf.data.business_no_request_1).click();
      await casePage.caseLoc.detail.btnDropdownBusiness.click();
      await expect(casePage.dashboardLoc.root).toMatchAriaSnapshot(`- text: Remove`);
    });

    await test.step("Add business through case update modal", async () => {
      await casePage.dashboardLoc.buttonByText("Update Case").click();
      await expect(casePage.dashboardLoc.modal.headerModal("Case Detail")).toBeVisible();
      await casePage.dashboardLoc.modal.inputByID("multi_select_provider_ids").type(conf.data.business_no_request_2, { delay: 100 });
      await casePage.caseLoc.create.detail.boxTextBusinessByName(conf.data.business_no_request_2).click();
      await casePage.dashboardLoc.modal.headerModal("Case Detail").click();
      await casePage.dashboardLoc.buttonByText("Update").first().click();
      await expect(casePage.caseLoc.detail.btnDropDownActionBySingleBusiness(conf.data.business_no_request_2)).toBeVisible();
      await expect(casePage.dashboardLoc.msgSuccess).toBeVisible();
      await casePage.dashboardLoc.btnClosePopupNotification.click();
    });

    await test.step("Add and remove businesses in detail view", async () => {
      // Add business
      await casePage.addBusinessInDetail(conf.data.business_no_request_3);
      await expect(casePage.caseLoc.detail.btnDropDownActionBySingleBusiness(conf.data.business_no_request_3)).toBeVisible();

      // Remove businesses
      await casePage.removeBusiness(conf.data.business_no_request_2);
      await casePage.removeBusiness(conf.data.business_no_request_3);
    });
  })
});
