<?php

namespace App\Http\Controllers\APIS\CustomerApi;

use App\Http\Controllers\Controller;
use App\Models\Device;
use App\Services\CustomerInfoService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class TimeseriesAlertMessageController extends Controller
{
    protected $customerInfoService;

    public function __construct(CustomerInfoService $customerInfoService)
    {
        $this->customerInfoService = $customerInfoService;
    }
    public function alertMessage(Request $request, $deviceId)
    {
        try {
            $token = readHeaderToken();
            if (!$token) {
                return response()->json([
                    'success' => false,
                    'message' => 'Authorization token required'
                ], 401);
            }

            $validator = Validator::make($request->all(), [
                'startTs' => 'nullable|numeric',
                'endTs' => 'nullable|numeric|gte:startTs',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->errors()->first()
                ], 400);
            }

            $device = Device::with([
                'timeseriesKeys' => function ($query) {
                    $query->where(function ($q) {
                        $q->where('display_on_dashboard', true)
                            ->orWhere('display_on_popup', true);
                    })
                    ->select('id', 'device_profile_xid', 'key_name', 'display_name')
                    ->with(['timeseriesAlert' => function ($query) {
                        $query->select('id', 'timeseries_key_master_xid', 'min_value', 'max_value', 'alert_msg');
                    }]);
                }
            ])->findOrFail($deviceId);

            $telemetryData = $this->customerInfoService->getTelemetryDataDevice(
                $device,
                $device->timeseriesKeys->pluck('key_name')->toArray(),
                $request->startTs,
                $request->endTs
            );

            if (isset($telemetryData['error'])) {
                throw new \Exception($telemetryData['error']);
            }

            $existingKeys = array_keys($telemetryData);
            $result = [];

            foreach ($device->timeseriesKeys as $key) {
                if (!in_array($key->key_name, $existingKeys, true)) {
                    continue;
                }

                $dataPoint = $telemetryData[$key->key_name][0] ?? null;
                if (!$dataPoint || !isset($dataPoint['value'])) {
                    continue;
                }

                $currentValue = (float)$dataPoint['value'];

                foreach ($key->timeseriesAlert as $alert) {
                    $minValue = $alert->min_value !== null ? (float)$alert->min_value : null;
                    $maxValue = $alert->max_value !== null ? (float)$alert->max_value : null;

                    $isBelowMin = $minValue !== null && $currentValue < $minValue;
                    $isAboveMax = $maxValue !== null && $currentValue > $maxValue;

                    if ($isBelowMin || $isAboveMax) {
                        // Convert alert message into an array and remove existing numbers
                        $formattedAlertMsg = array_map(
                            fn($line, $index) => ($index + 1) . ". " . preg_replace('/^\d+\.\s*/', '', trim($line)),
                            explode(";", $alert->alert_msg),
                            array_keys(explode(";", $alert->alert_msg))
                        );

                        $result[] = [
                            'device_id' => $device->id,
                            'key_name' => $key->key_name,
                            'display_name' => $key->display_name,
                            'alert_msg' => $formattedAlertMsg,
                        ];
                        break; // Stop at the first matching alert
                    }
                }
            }

            return response()->json([
                'success' => true,
                'alerts' => $result
            ]);

        } catch (\Exception $e) {
            Log::error("Alert processing failed: {$e->getMessage()}", [
                'device_id' => $deviceId ?? null,
                'trace' => $e->getTraceAsString()
            ]);

            return response()->json([
                'success' => false,
                'message' => 'Failed to process alerts: ' . $e->getMessage()
            ], 500);
        }
    }

    // public function alertMessage(Request $request)
    // {
    //     try {
    //         $token = readHeaderToken();
    //         if (!$token) {
    //             return response()->json([
    //                 'success' => false,
    //                 'message' => 'Authorization token required'
    //             ], 401);
    //         }

    //         $validator = Validator::make($request->all(), [
    //             'device_id' => 'required|string|exists:devices,id',
    //             'startTs' => 'nullable|numeric',
    //             'endTs' => 'nullable|numeric|gte:startTs',
    //         ]);

    //         if ($validator->fails()) {
    //             return response()->json([
    //                 'success' => false,
    //                 'message' => $validator->errors()->first()
    //             ], 400);
    //         }

    //         $device = Device::with([
    //             'timeseriesKeys' => function ($query) {
    //                 $query->where(function ($q) {
    //                     $q->where('display_on_dashboard', true)
    //                         ->orWhere('display_on_popup', true);
    //                 })
    //                 ->select('id', 'device_profile_xid', 'key_name', 'display_name')
    //                 ->with(['timeseriesAlert' => function ($query) {
    //                     $query->select('id', 'timeseries_key_master_xid', 'min_value', 'max_value', 'alert_msg');
    //                 }]);
    //             }
    //         ])->findOrFail($request->device_id);

    //         $telemetryData = $this->customerInfoService->getTelemetryDataDevice(
    //             $device,
    //             $device->timeseriesKeys->pluck('key_name')->toArray(),
    //             $request->startTs,
    //             $request->endTs
    //         );

    //         if (isset($telemetryData['error'])) {
    //             throw new \Exception($telemetryData['error']);
    //         }

    //         $existingKeys = array_keys($telemetryData);
    //         $result = [];

    //         foreach ($device->timeseriesKeys as $key) {
    //             if (!in_array($key->key_name, $existingKeys, true)) {
    //                 continue;
    //             }

    //             $dataPoint = $telemetryData[$key->key_name][0] ?? null;
    //             if (!$dataPoint || !isset($dataPoint['value'])) {
    //                 continue;
    //             }

    //             $currentValue = (float)$dataPoint['value'];

    //             foreach ($key->timeseriesAlert as $alert) {
    //                 $minValue = $alert->min_value !== null ? (float)$alert->min_value : null;
    //                 $maxValue = $alert->max_value !== null ? (float)$alert->max_value : null;

    //                 $isBelowMin = $minValue !== null && $currentValue < $minValue;
    //                 $isAboveMax = $maxValue !== null && $currentValue > $maxValue;

    //                 if ($isBelowMin || $isAboveMax) {
    //                     // Convert alert message into an array and remove existing numbers
    //                     $formattedAlertMsg = array_map(
    //                         fn($line, $index) => ($index + 1) . ". " . preg_replace('/^\d+\.\s*/', '', trim($line)),
    //                         explode(";", $alert->alert_msg),
    //                         array_keys(explode(";", $alert->alert_msg))
    //                     );

    //                     $result[] = [
    //                         'device_id' => $device->id,
    //                         'key_name' => $key->key_name,
    //                         'display_name' => $key->display_name,
    //                         'alert_msg' => $formattedAlertMsg, // Return as an array
    //                     ];
    //                     break; // Stop at the first matching alert
    //                 }
    //             }



    //         }

    //         return response()->json([
    //             'success' => true,
    //             'alerts' => $result
    //         ]);

    //     } catch (\Exception $e) {
    //         Log::error("Alert processing failed: {$e->getMessage()}", [
    //             'device_id' => $request->device_id ?? null,
    //             'trace' => $e->getTraceAsString()
    //         ]);

    //         return response()->json([
    //             'success' => false,
    //             'message' => 'Failed to process alerts: ' . $e->getMessage()
    //         ], 500);
    //     }
    // }

}
