import { test, expect } from '@playwright/test';
import { addProductToCart, mockShopApi } from './helpers';

test('checkout shows error when order submission fails', async ({ page }) => {
  await mockShopApi(page);

  await page.route('**/api/orders', async (route) => {
    await route.fulfill({
      status: 500,
      contentType: 'application/json',
      body: JSON.stringify({ error: 'Failed to create order' }),
    });
  });

  await page.goto('/kauppa');
  await addProductToCart(page, 'Supair Evo Lite');
  await page.getByRole('link', { name: /Ostoskori/ }).click();
  await page.getByRole('button', { name: /Siirry kassalle/ }).click();

  await page.locator('input[name="name"]').fill('Testi Asiakas');
  await page.locator('input[name="email"]').fill('testi@example.com');
  await page.locator('input[name="phone"]').fill('040 123 4567');
  await page.locator('input[name="address"]').fill('Testikatu 1');
  await page.locator('input[name="zip"]').fill('00100');
  await page.locator('input[name="city"]').fill('Helsinki');
  await page.locator('textarea[name="notes"]').fill('Toimitus ohjeilla.');

  await page.locator('label:has-text("Olen lukenut") div').first().click();
  await page.getByRole('button', { name: /Vahvista tilaus/ }).click();

  await expect(
    page.getByText('Jotain meni pieleen. Tilausta ei voitu lähettää. Yritä uudelleen.'),
  ).toBeVisible();
  await expect(page.getByRole('heading', { name: /Kiitos tilauksestasi/i })).not.toBeVisible();
});
