import { randomUUID } from 'node:crypto';
import type { DestinationStream } from 'pino';
import type pg from 'pg';
import { afterAll, afterEach, 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)('checkout 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: 'checkout-user@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']);

    const zone = await app.inject({
      method: 'POST',
      url: '/shipping/zones',
      headers: { 'content-type': 'application/json' },
      cookies: { [SESSION_COOKIE_NAME]: cookie },
      payload: { name: 'Peninsula', country: 'ES', postalCodePrefix: '28' },
    });
    const zoneId = (zone.json() as { id: string }).id;
    await app.inject({
      method: 'POST',
      url: '/shipping/methods',
      headers: { 'content-type': 'application/json' },
      cookies: { [SESSION_COOKIE_NAME]: cookie },
      payload: { zoneId, name: 'Standard', baseCostCents: 500 },
    });
  });

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

  afterEach(async () => {
    await pool.query('DELETE FROM cart_items');
    await pool.query('DELETE FROM cart_carts');
  });

  async function seedCart(variantId: string, cents = 1000, stock = 5) {
    const productId = randomUUID();
    await app.inject({
      method: 'PUT',
      url: `/pricing/variants/${variantId}`,
      headers: { 'content-type': 'application/json' },
      cookies: { [SESSION_COOKIE_NAME]: cookie },
      payload: { netUnitAmountCents: cents, vatRate: 'general' },
    });
    await app.inject({
      method: 'PUT',
      url: `/inventory/${variantId}/stock`,
      headers: { 'content-type': 'application/json' },
      cookies: { [SESSION_COOKIE_NAME]: cookie },
      payload: { quantity: stock },
    });
    await app.inject({
      method: 'POST',
      url: '/cart/items',
      headers: { 'content-type': 'application/json' },
      cookies: { [SESSION_COOKIE_NAME]: cookie },
      payload: { productId, variantId, quantity: 1 },
    });
  }

  it('returns 409 without creating order when cart has out-of-stock item (AC1)', async () => {
    const variantId = randomUUID();
    await seedCart(variantId, 1000, 0);
    const idempotencyKey = randomUUID();
    const response = await app.inject({
      method: 'POST',
      url: '/checkout',
      headers: { 'content-type': 'application/json' },
      cookies: { [SESSION_COOKIE_NAME]: cookie },
      payload: { address: { country: 'ES', postalCode: '28001' }, idempotencyKey },
    });
    expect(response.statusCode).toBe(409);
    expect((response.json().error as { code: string }).code).toBe('CHECKOUT_STOCK_UNAVAILABLE');
    const orderRows = await pool.query('SELECT id FROM orders_orders WHERE idempotency_key = $1', [
      idempotencyKey,
    ]);
    expect(orderRows.rowCount).toBe(0);
  });

  it('returns the same order on idempotent retry without duplicate reservation (AC2)', async () => {
    const variantId = randomUUID();
    await seedCart(variantId, 1000, 5);
    const idempotencyKey = randomUUID();
    const first = await app.inject({
      method: 'POST',
      url: '/checkout',
      headers: { 'content-type': 'application/json' },
      cookies: { [SESSION_COOKIE_NAME]: cookie },
      payload: { address: { country: 'ES', postalCode: '28001' }, idempotencyKey },
    });
    expect(first.statusCode).toBe(200);
    const orderId = (first.json() as { order: { id: string } }).order.id;

    const stockBefore = await pool.query<{ available: number; reserved: number }>(
      'SELECT available, reserved FROM inventory_stock WHERE variant_id = $1',
      [variantId],
    );

    const second = await app.inject({
      method: 'POST',
      url: '/checkout',
      headers: { 'content-type': 'application/json' },
      cookies: { [SESSION_COOKIE_NAME]: cookie },
      payload: { address: { country: 'ES', postalCode: '28001' }, idempotencyKey },
    });
    expect(second.statusCode).toBe(200);
    expect((second.json() as { order: { id: string } }).order.id).toBe(orderId);

    const stockAfter = await pool.query<{ available: number; reserved: number }>(
      'SELECT available, reserved FROM inventory_stock WHERE variant_id = $1',
      [variantId],
    );
    expect(stockAfter.rows[0]).toEqual(stockBefore.rows[0]);
  });

  it('creates an AWAITING_PAYMENT order with reserved stock (AC3)', async () => {
    const variantId = randomUUID();
    await seedCart(variantId, 1000, 5);
    const response = await app.inject({
      method: 'POST',
      url: '/checkout',
      headers: { 'content-type': 'application/json' },
      cookies: { [SESSION_COOKIE_NAME]: cookie },
      payload: { address: { country: 'ES', postalCode: '28001' }, idempotencyKey: randomUUID() },
    });
    expect(response.statusCode).toBe(200);
    expect((response.json() as { order: { state: string } }).order.state).toBe('AWAITING_PAYMENT');
    const stock = await pool.query<{ available: number; reserved: number }>(
      'SELECT available, reserved FROM inventory_stock WHERE variant_id = $1',
      [variantId],
    );
    expect(stock.rows[0]).toEqual({ available: 4, reserved: 1 });
  });
});
