<?php

declare(strict_types=1);

namespace Kylin\Agriculture\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Kylin\Agriculture\Jobs\ProcessSensorData;
use Kylin\Agriculture\Models\Sensor;

/**
 * 传感器数据控制器
 *
 * 接收传感器上报数据，通过队列异步处理。
 */
class SensorDataController
{
    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'device_id' => 'required|string|exists:sensors,device_id',
            'parameters' => 'required|array',
            'collected_at' => 'required|date',
        ]);

        $sensor = Sensor::where('device_id', $validated['device_id'])->first();

        // 更新传感器最后数据时间
        $sensor->update(['last_data_at' => now()]);

        // 异步处理传感器数据
        ProcessSensorData::dispatch(
            $sensor->id,
            $validated['parameters'],
            $validated['collected_at'],
        );

        return response()->json([
            'code' => 'SUCCESS',
            'message' => '数据接收成功',
        ]);
    }
}
