<?php

namespace App\Modules\Integration\Controllers;

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

class OrderSyncController extends Controller
{
    protected $syncOrderAction;

    public function __construct(SyncOrderAction $syncOrderAction)
    {
        $this->syncOrderAction = $syncOrderAction;
    }

    /**
     * 接收並同步外部交易訂單
     *
     * @param SyncOrderRequest $request
     * @return JsonResponse
     */
    public function store(SyncOrderRequest $request): JsonResponse
    {
        try {
            // 所有驗證皆已透過 SyncOrderRequest 自動處理
            // 將通過驗證的資料交由 Action 處理（包含併發鎖、預先驗證、與資料庫異動）
            $result = $this->syncOrderAction->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) {
            // 捕捉 Action 中拋出的預先驗證錯誤 (如查無商品、或鎖定逾時)
            return response()->json([
                'message' => 'Validation failed',
                'errors' => $e->errors()
            ], 422);

        } catch (\Exception $e) {
            // 系統層級的錯誤
            Log::error('Order Sync Failed', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
                'payload' => $request->all()
            ]);
            
            return response()->json([
                'message' => 'Sync failed: An unexpected error occurred.'
            ], 500);
        }
    }
}
