import { test, expect } from "@playwright/test";
import { PrismaClient } from "@prisma/client";
import { bookOneAdult } from "../../fixtures/booking-flow";
import { PROMO_VALID } from "../../fixtures/data";

const prisma = new PrismaClient();
test.afterAll(async () => {
  await prisma.$disconnect();
});

/**
 * UA-8 ✅ — a VALID promo is applied server-side even though the browser drops it (H-13). The portal
 * still sums UNDISCOUNTED per-passenger fares into reviewedTotalMinor, but the server recomputes the
 * authoritative fare (promo included, via the promoCode it forwards) and books the DISCOUNTED total —
 * so the customer is charged the promo price, not full price.
 */
test("UA-8: valid promo is applied server-side to the booked total (H-13)", async ({ page }) => {
  const r = await bookOneAdult(page, {
    nationality: "Ethiopian",
    paymentMethod: "WALLET",
    promoCode: PROMO_VALID,
  });

  const fb = r.fareBreakdown;
  expect(fb).toBeTruthy();

  // The breakdown recognized the promo and computed a discount…
  expect(fb.discountMinor).toBeGreaterThan(0);
  expect(fb.totalMinor).toBeLessThan(fb.subtotalMinor);

  // The browser still sends the UNDISCOUNTED subtotal (the frontend drops the promo)…
  expect(r.reviewedTotalMinor).toBe(fb.subtotalMinor);
  // …but the SERVER now applies the promo: the booking is stored at the discounted total.
  const booking = await prisma.booking.findUniqueOrThrow({ where: { id: r.bookingId } });
  expect(booking.totalMinor).toBeLessThan(fb.subtotalMinor); // ✅ discount honored
  expect(booking.totalMinor).toBe(fb.subtotalMinor - fb.discountMinor);
});
