/**
 * POST /api/payment/mock-paypal
 *
 * Mock PayPal payment endpoint for MVP development
 *
 * This endpoint simulates a PayPal payment without making actual API calls.
 * It's used for testing the checkout flow end-to-end before real PayPal integration.
 *
 * Request Body:
 * {
 *   orderId: string (UUID)
 * }
 *
 * Behavior:
 * - Validates order exists and belongs to logged-in user
 * - Validates order status is 'pending'
 * - Returns immediate "success" response with mock payment ID
 * - Does NOT update order status (that happens in /api/orders/confirm/[id])
 *
 * Response:
 * {
 *   success: true,
 *   paymentId: string (mock ID),
 *   message: string
 * }
 *
 * Errors:
 * - 401: Not authenticated
 * - 400: Invalid request
 * - 404: Order not found
 */

import { z } from 'zod'
import { eq, and } from 'drizzle-orm'
import { orders } from '../../database/schema'

const mockPaymentSchema = z.object({
  orderId: z.string().uuid('Invalid order ID'),
})

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

  // 2. Validate request body
  const body = await readBody(event)
  const { orderId } = await mockPaymentSchema.parseAsync(body)

  const db = useDatabase()

  // 3. Fetch order
  const order = await db.query.orders.findFirst({
    where: and(eq(orders.id, orderId), eq(orders.userId, user.id)),
  })

  if (!order) {
    throw createError({
      statusCode: 404,
      statusMessage: 'Order not found',
      message: 'Bestellung wurde nicht gefunden',
    })
  }

  // 4. Validate order status
  if (order.status !== 'pending') {
    throw createError({
      statusCode: 400,
      statusMessage: 'Invalid order status',
      message: `Bestellung kann nicht bezahlt werden. Status: ${order.status}`,
    })
  }

  // 5. Simulate PayPal processing delay (optional)
  // In real implementation, this would be replaced with actual PayPal API call
  await new Promise((resolve) => setTimeout(resolve, 500)) // 500ms delay

  // 6. Generate mock payment ID
  const mockPaymentId = `MOCK-PAYPAL-${Date.now()}-${orderId.slice(0, 8)}`

  // 7. Return success response
  // Note: Order status is NOT updated here. That happens in /api/orders/confirm/[id]
  return {
    success: true,
    paymentId: mockPaymentId,
    message: 'Mock-Zahlung erfolgreich',
  }
})
