<?php

namespace App\Modules\Integration\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\Integration\Requests\SyncVendingOrderRequest;
use App\Modules\Integration\Actions\SyncVendingOrderAction;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;

class VendingOrderSyncController extends Controller
{
    protected $syncVendingOrderAction;

    public function __construct(SyncVendingOrderAction $syncVendingOrderAction)
    {
        $this->syncVendingOrderAction = $syncVendingOrderAction;
    }

    /**
     * 接收並同步販賣機交易訂單
     *
     * @param SyncVendingOrderRequest $request
     * @return JsonResponse
     */
    public function store(SyncVendingOrderRequest $request): JsonResponse
    {
        try {
            $result = $this->syncVendingOrderAction->execute($request->validated());

            $statusCode = ($result['status'] === 'exists') ? 200 : 201;

            return response()->json([
                'message' => $result['message'],
                'order_id' => $result['order_id'] ?? null,
            ], $statusCode);

        } catch (\Illuminate\Validation\ValidationException $e) {
            return response()->json([
                'message' => 'Validation failed',
                'errors' => $e->errors()
            ], 422);

        } catch (\Exception $e) {
            Log::error('Vending Order Sync Failed', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
                'payload' => $request->all()
            ]);

            return response()->json([
                'message' => 'Sync failed: An unexpected error occurred.'
            ], 500);
        }
    }
}
