const { test, expect } = require('@playwright/test');

const FAKE_TOKEN = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjk5OTk5OTk5OTksIm5hbWUiOiJUZXN0IFVzZXIifQ.signature';

async function setupAuth(page) {
  await page.goto('/pos/login');
  await page.evaluate((token) => {
    localStorage.setItem('pos_token', token);
    localStorage.setItem('pos_tenant_id', '11');
  }, FAKE_TOKEN);
}

async function mockPOSAPIs(page) {
  await page.route('/pos/api/register/current', async (route) => {
    await route.fulfill({
      status: 200,
      contentType: 'application/json',
      body: JSON.stringify({ register: { register_number: 1 } }),
    });
  });

  await page.route(/\/pos\/api\/inventory\/items\?q=.*&per_page=.*/, async (route) => {
    await route.fulfill({
      status: 200,
      contentType: 'application/json',
      body: JSON.stringify({
        data: [
          {
            id: 1,
            part_number: 'TEST-001',
            name: 'Producto de prueba',
            brand: 'TestBrand',
            stock: 10,
            price_1: 100.0,
            price_2: 90.0,
            price_3: 80.0,
          },
        ],
      }),
    });
  });
}

test.describe('Nexus POS — Checkout', () => {
  test('POS page loads with cart', async ({ page }) => {
    await setupAuth(page);
    await mockPOSAPIs(page);
    await page.goto('/pos/sale');

    await expect(page).toHaveTitle(/Nexus Autoparts/i);
    await expect(page.locator('#cartItems')).toBeVisible();
    await expect(page.locator('#cartBody')).toBeVisible();
    await expect(page.locator('#btnCobrar')).toBeVisible();
  });

  test('catalog search from POS', async ({ page }) => {
    await setupAuth(page);
    await mockPOSAPIs(page);
    await page.goto('/pos/sale');

    const searchInput = page.locator('#itemSearch');
    await expect(searchInput).toBeVisible();
    await searchInput.fill('test');
    await searchInput.press('Enter');

    // Assert search results dropdown/grid appears
    const results = page.locator('#searchResults');
    await expect(results).toBeVisible({ timeout: 5000 });
    await expect(results).toContainText('Producto de prueba');
  });
});
