<?php

namespace App\Jobs\Transaction;

use App\Models\Machine\Machine;
use App\Services\Transaction\TransactionService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use App\Jobs\Machine\ProcessStateLog;

class ProcessTransactionFinalized implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $serialNo;
    protected $payload;

    /**
     * Create a new job instance.
     */
    public function __construct(string $serialNo, array $payload)
    {
        $this->serialNo = $serialNo;
        $this->payload = $payload;
    }

    /**
     * Execute the job.
     */
    public function handle(\App\Services\Transaction\TransactionService $transactionService, \App\Services\Machine\MqttService $mqttService): void
    {
        $machine = Machine::withoutGlobalScopes()->where('serial_no', $this->serialNo)->first();

        if (!$machine) {
            Log::warning("MQTT Transaction Finalized: Machine not found", ['serial_no' => $this->serialNo]);
            return;
        }

        $flowId = $this->payload['order']['flow_id'] ?? ($this->payload['flow_id'] ?? 'N/A');

        try {
            $data = $this->payload;
            $data['serial_no'] = $this->serialNo;

            $order = $transactionService->finalizeTransaction($data);

            ProcessStateLog::dispatch(
                $machine->id,
                $machine->company_id,
                "Transaction finalized: :id",
                'info',
                [
                    'id' => $order->order_no,
                    'flow_id' => $order->flow_id
                ],
                'transaction'
            );
            
            Log::info("MQTT Transaction [finalize] processed successfully", [
                'serial_no' => $this->serialNo,
                'order_no' => $order->order_no
            ]);

            // 發送成功回饋 (ACK)
            $mqttService->pushCommand($this->serialNo, 'transaction_ack', [
                'flow_id' => $flowId,
                'order_no' => $order->order_no,
                'status' => 'success',
                'message' => 'Processed successfully'
            ], (string) $flowId);

        } catch (\Exception $e) {
            Log::error("Failed to process MQTT transaction finalized for machine {$this->serialNo}: " . $e->getMessage(), [
                'payload' => $this->payload,
                'exception' => $e
            ]);

            // 發送失敗回饋 (ACK)
            $mqttService->pushCommand($this->serialNo, 'transaction_ack', [
                'flow_id' => $flowId,
                'status' => 'error',
                'message' => $e->getMessage()
            ], (string) $flowId);

            throw $e;
        }
    }
}
