/**
 * POST /api/checkout/validate
 *
 * Validates checkout data before creating an order
 *
 * Request Body:
 * {
 *   salutation: 'male' | 'female' | 'other',
 *   firstName: string,
 *   lastName: string,
 *   dateOfBirth: string (YYYY-MM-DD),
 *   street: string,
 *   postCode: string (5 digits),
 *   city: string,
 *   countryCode: string (ISO 3166-1 alpha-2, default: 'DE'),
 *   saveAddress: boolean (optional)
 * }
 *
 * Response:
 * {
 *   success: true,
 *   message: string
 * }
 *
 * Errors:
 * - 401: Not authenticated
 * - 400: Empty cart
 * - 422: Validation errors
 */

import { checkoutSchema } from '../../utils/schemas/checkout'

export default defineEventHandler(async (event) => {
  // 1. Require authentication
  const { user } = await requireUserSession(event)

  // 2. Check if cart has items
  const cart = await getOrCreateCart(event)
  const cartSummary = await getCartWithItems(cart.id)

  if (cartSummary.itemCount === 0) {
    throw createError({
      statusCode: 400,
      statusMessage: 'Cart is empty',
      message: 'Dein Warenkorb ist leer. Füge Produkte hinzu, um fortzufahren.',
    })
  }

  // 3. Validate checkout data
  const body = await readBody(event)

  try {
    const validatedData = await checkoutSchema.parseAsync(body)

    return {
      success: true,
      message: 'Checkout-Daten sind gültig',
      data: validatedData,
    }
  } catch (error: any) {
    // Zod validation errors
    if (error.errors) {
      throw createError({
        statusCode: 422,
        statusMessage: 'Validation error',
        message: 'Bitte überprüfe deine Eingaben',
        data: error.errors,
      })
    }

    // Unknown error
    throw error
  }
})
