/**
 * Copyright (C) 2025 Brainformatik GmbH
 *
 * 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 { ContactDetailPage } from '../utils/pageObjects/ContactDetailPage.js';
import { ContactsListPage } from '../utils/pageObjects/ContactsListPage.js';
import { LoginPage } from '../utils/pageObjects/LoginPage.js';

const loginAndLoadContacts = async (page) => {
  const login = new LoginPage(page);
  const contacts = new ContactsListPage(page);
  await login.goto('?redirect=/contacts');
  await login.signIn({
    username: 'admin',
    password: 'admin' 
  });
  await page.waitForURL('**/contacts', {
    timeout: 60000 
  });
  await contacts.waitForLoaded();
  return contacts;
};

test.describe('Contact detail navigation + resilience', () => {
  test('opens contact detail from list view and shows hero', async ({
    page 
  }) => {
    const contacts = await loginAndLoadContacts(page);
    const detail = new ContactDetailPage(page);

    const jamieId = await contacts.contactIdByName('Delgado, Jamie');
    await contacts.openDetail(jamieId);

    await page.waitForURL(/\/contacts\/[A-Za-z0-9_-]+$/, {
      timeout: 60000 
    });
    await detail.waitForHero('Jamie Delgado');
    await expect(detail.quickActions()).toHaveCount(3);
    await expect(detail.detailLinks()).toHaveCount(3);
    await expect(detail.relatedLinks()).toHaveCount(2);
    await expect(detail.visitReportsTile()).toContainText('Visit Reports');
  });

  test('falls back to cached data when detail API fails and recovers afterwards', async ({
    page 
  }) => {
    const contacts = await loginAndLoadContacts(page);
    const detail = new ContactDetailPage(page);

    const failurePatterns = [
      '**/entity/**/records/**',
      '**/relations/**'
    ];

    for (const pattern of failurePatterns) {
      await page.route(pattern, (route) => {
        route.fulfill({
          status: 503,
          headers: {
            'content-type': 'application/json' 
          },
          body: JSON.stringify({
            status: 503,
            message: 'Service unavailable' 
          })
        });
      });
    }

    const jamieId = await contacts.contactIdByName('Delgado, Jamie');
    await contacts.openDetail(jamieId);
    await page.waitForURL(/\/contacts\/[A-Za-z0-9_-]+$/, {
      timeout: 60000 
    });
    await detail.waitForHero('Jamie Delgado');
    await expect(detail.errorBanner()).toHaveCount(0);

    // relations API failed, but cached highlight should still render in demo/offline mode
    await expect(detail.visitReportsTile()).toHaveCount(1);
    await expect(detail.visitReportsTile()).toContainText('Visit Reports');

    // remove failure routes and reload to ensure fresh data arrives
    for (const pattern of failurePatterns) {
      await page.unroute(pattern);
    }
    await detail.reload();
    await detail.waitForHero('Jamie Delgado');
    await expect(detail.visitReportsTile()).toHaveCount(1);
  });

  test('list swiping still works after visiting detail', async ({
    page, intentRecorder 
  }) => {
    const contacts = await loginAndLoadContacts(page);
    const detail = new ContactDetailPage(page);

    const jamieId = await contacts.contactIdByName('Delgado, Jamie');
    await contacts.openDetail(jamieId);
    await page.waitForURL(/\/contacts\/[A-Za-z0-9_-]+$/, {
      timeout: 60000 
    });
    await detail.waitForHero('Jamie Delgado');

    await detail.goBack();
    await page.waitForURL('**/contacts', {
      timeout: 60000 
    });
    await contacts.waitForLoaded();

    await contacts.openCallSheet(jamieId);
    await contacts.bottomSheetOptions().first().waitFor({
      state: 'visible' 
    });
    await contacts.chooseBottomSheetOption('+49 30 123456');
    await expect.poll(async () => intentRecorder.lastIntent()).toBe('tel:+4930123456');
  });
});
