<?php

declare(strict_types=1);

namespace Kylin\Agriculture\Jobs;

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\DB;
use Illuminate\Support\Facades\Log;
use Kylin\Agriculture\Models\SensorData;

/**
 * 传感器数据处理 Job
 *
 * 异步处理传感器上报的原始数据，存入数据库。
 */
class ProcessSensorData implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public int $tries = 3;
    public int $timeout = 60;

    public function __construct(
        public int $sensorId,
        public array $parameters,
        public string $collectedAt,
    ) {}

    public function handle(): void
    {
        DB::transaction(function () {
            SensorData::create([
                'sensor_id' => $this->sensorId,
                'parameters' => $this->parameters,
                'collected_at' => $this->collectedAt,
                'created_at' => now(),
            ]);
        });

        // 触发预警检测
        CheckWarningRules::dispatch($this->sensorId, $this->parameters);
    }
}
