<?php

namespace App\Jobs\Machine;

use App\Models\Machine\Machine;
use App\Models\Machine\TimerStatus;
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;

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

    protected $serialNo;
    protected $data;

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

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        try {
            $machine = Machine::where('serial_no', $this->serialNo)->firstOrFail();
            
            TimerStatus::updateOrCreate(
                ['machine_id' => $machine->id, 'slot_no' => $this->data['slot_no']],
                [
                    'status' => $this->data['status'],
                    'remaining_seconds' => $this->data['remaining_seconds'],
                    'end_at' => isset($this->data['end_at']) ? \Carbon\Carbon::parse($this->data['end_at']) : null,
                ]
            );
        } catch (\Exception $e) {
            Log::error("Failed to process timer status for machine {$this->serialNo}: " . $e->getMessage());
            throw $e;
        }
    }
}
