/**
 * Copyright (C) 2025 Brainformatik GmbH (info@brainformatik.com)
 *
 * This file is part of brainX.
 * All Rights Reserved.
 *
 * This part of brainX can not be copied and/or distributed without the
 * express permission of Brainformatik GmbH.
 */

import { test, expect } from '../fixtures/app.fixture.js';
import { LoginPage } from '../utils/pageObjects/LoginPage.js';

test.describe('VisitReport attachments', () => {
  test('keeps existing attachments when uploading and deleting', async ({
    page, mockApi 
  }) => {
    void mockApi;
    const login = new LoginPage(page);

    await login.goto('?redirect=/visitreport/demo-report-1/attachments');
    await login.signIn({
      username: 'admin',
      password: 'admin' 
    });
    await page.waitForURL('**/visitreport/demo-report-1/attachments', {
      timeout: 60000
    });

    const list = page.locator('[data-test="visit-report-attachments-list"]');
    await list.waitFor({
      state: 'visible' 
    });
    await expect(list.locator('article')).toHaveCount(2);

    const uploadRequestPromise = page.waitForRequest((request) => {
      return request.method() === 'PATCH' && request.url().includes('/entity/204/records/demo-report-1');
    });
    await page.locator('input[type="file"]').setInputFiles({
      name: 'Notes.pdf',
      mimeType: 'application/pdf',
      buffer: Buffer.from('notes')
    });
    const uploadRequest = await uploadRequestPromise;
    const uploadPayload = uploadRequest.postDataJSON();
    expect(uploadPayload.attachments_block_dummy).toEqual(
      expect.arrayContaining([
        {
          name: 'meeting-notes.pdf',
          attachmentsid: 'visit-attachment-1' 
        },
        {
          name: 'showroom-photo.jpg',
          attachmentsid: 'visit-attachment-2' 
        },
        expect.objectContaining({
          name: 'Notes.pdf' 
        })
      ])
    );

    await expect(page.getByText('Notes.pdf')).toBeVisible();

    const deleteRequestPromise = page.waitForRequest((request) => {
      return request.method() === 'PATCH' && request.url().includes('/entity/204/records/demo-report-1');
    });
    const scanCard = page.locator('[data-test="visit-report-attachments-list"] article', {
      hasText: 'meeting-notes.pdf'
    });
    await scanCard.locator('[data-testid^="btn-attachment-remove-"]').click();

    const deleteRequest = await deleteRequestPromise;
    const deletePayload = deleteRequest.postDataJSON();
    expect(deletePayload.attachments_block_dummy.some((entry) => entry.name === 'meeting-notes.pdf')).toBe(false);
    expect(deletePayload.attachments_block_dummy.some((entry) => entry.name === 'showroom-photo.jpg')).toBe(true);
    expect(deletePayload.attachments_block_dummy.some((entry) => entry.name === 'Notes.pdf')).toBe(true);

    await expect(page.getByText('meeting-notes.pdf')).toHaveCount(0);
  });
});
