import { randomUUID } from 'node:crypto';
import type { DestinationStream } from 'pino';
import type pg from 'pg';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { buildApp } from '../build-app.js';
import { createPool } from '../../infrastructure/db/pool.js';
import { createLogger } from '../../infrastructure/logging/logger.js';
import {
  getTestDbUrl,
  recreateDatabase,
  runMigrations,
} from '../../infrastructure/db/tests/db-test-support.js';
import { SESSION_COOKIE_NAME } from '../../modules/identity/index.js';

const hasDb = Boolean(process.env.TEST_DATABASE_URL);
function silentLogger() {
  const destination: DestinationStream = { write: () => undefined };
  return createLogger({ level: 'info', destination });
}
function cookieValue(setCookieHeader: string | string[] | undefined): string {
  const raw = Array.isArray(setCookieHeader) ? setCookieHeader[0] : setCookieHeader;
  expect(raw).toBeDefined();
  const pair = (raw as string).split(';')[0] as string;
  return pair.slice(pair.indexOf('=') + 1);
}

describe.skipIf(!hasDb)('cart flows (real PostgreSQL)', () => {
  const url = hasDb ? getTestDbUrl() : '';
  let pool: pg.Pool;
  let app: Awaited<ReturnType<typeof buildApp>>;
  let cookie = '';

  beforeAll(async () => {
    await recreateDatabase(url);
    await runMigrations(url, 'up');
    pool = createPool(url);
    app = await buildApp({ logger: silentLogger(), pool, cookieSecure: true });
    const user = { email: 'cart-admin@example.com', password: 'correct horse battery staple' };
    const registered = await app.inject({
      method: 'POST',
      url: '/auth/register',
      headers: { 'content-type': 'application/json' },
      payload: user,
    });
    const id = (registered.json() as { id: string }).id;
    await pool.query('UPDATE identity_users SET role = $1 WHERE id = $2', ['admin', id]);
    const login = await app.inject({
      method: 'POST',
      url: '/auth/login',
      headers: { 'content-type': 'application/json' },
      payload: user,
    });
    cookie = cookieValue(login.headers['set-cookie']);
  });

  afterAll(async () => {
    await app.close();
    await pool.end();
  });

  async function setPrice(variantId: string, cents: number) {
    await app.inject({
      method: 'PUT',
      url: `/pricing/variants/${variantId}`,
      headers: { 'content-type': 'application/json' },
      cookies: { [SESSION_COOKIE_NAME]: cookie },
      payload: { netUnitAmountCents: cents, vatRate: 'general' },
    });
  }

  async function setStock(variantId: string, quantity: number) {
    await app.inject({
      method: 'PUT',
      url: `/inventory/${variantId}/stock`,
      headers: { 'content-type': 'application/json' },
      cookies: { [SESSION_COOKIE_NAME]: cookie },
      payload: { quantity },
    });
  }

  it('recalculates cart totals when product price changes after add (AC1)', async () => {
    const productId = randomUUID();
    const variantId = randomUUID();
    await setPrice(variantId, 1000);
    await setStock(variantId, 10);
    await app.inject({
      method: 'POST',
      url: '/cart/items',
      headers: { 'content-type': 'application/json' },
      cookies: { [SESSION_COOKIE_NAME]: cookie },
      payload: { productId, variantId, quantity: 2 },
    });
    await setPrice(variantId, 2000);

    const cart = await app.inject({
      method: 'GET',
      url: '/cart',
      cookies: { [SESSION_COOKIE_NAME]: cookie },
    });
    expect(cart.statusCode).toBe(200);
    expect(cart.json()).toMatchObject({
      netSubtotalCents: 4000,
      vatAmountCents: 840,
      totalCents: 4840,
    });
  });

  it('flags cart item unavailable when variant is out of stock (AC2)', async () => {
    const productId = randomUUID();
    const variantId = randomUUID();
    await setPrice(variantId, 500);
    await setStock(variantId, 0);
    await app.inject({
      method: 'POST',
      url: '/cart/items',
      headers: { 'content-type': 'application/json' },
      cookies: { [SESSION_COOKIE_NAME]: cookie },
      payload: { productId, variantId, quantity: 1 },
    });

    const cart = await app.inject({
      method: 'GET',
      url: '/cart',
      cookies: { [SESSION_COOKIE_NAME]: cookie },
    });
    const item = (cart.json().items as Array<{ variantId: string; available: boolean }>).find(
      (entry) => entry.variantId === variantId,
    );
    expect(item).toMatchObject({ available: false });
  });

  it('ignores client-supplied price fields in cart payloads (AC3)', async () => {
    const productId = randomUUID();
    const variantId = randomUUID();
    await setPrice(variantId, 700);
    await setStock(variantId, 3);
    const response = await app.inject({
      method: 'POST',
      url: '/cart/items',
      headers: { 'content-type': 'application/json' },
      cookies: { [SESSION_COOKIE_NAME]: cookie },
      payload: { productId, variantId, quantity: 1, netUnitAmountCents: 1, totalCents: 1 },
    });

    expect(response.statusCode).toBe(201);
    const item = (
      response.json().items as Array<{
        variantId: string;
        pricing: { netSubtotalCents: number; vatAmountCents: number; totalCents: number };
      }>
    ).find((entry) => entry.variantId === variantId);
    expect(item?.pricing).toMatchObject({
      netSubtotalCents: 700,
      vatAmountCents: 147,
      totalCents: 847,
    });
    const columns = await pool.query(
      "SELECT column_name FROM information_schema.columns WHERE table_name = 'cart_items'",
    );
    expect(columns.rows.map((row) => row.column_name).join(' ')).not.toMatch(
      /price|tax|vat|discount|stock/i,
    );
  });
});
