<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Cache;
use Exception;
use Illuminate\Support\Facades\Log;


class DeviceService
{
    private $baseUrl;
    private $username;
    private $password;

    public function __construct()
    {
        $this->baseUrl = env('THINGSBOARD_URL', 'http://65.0.131.117:8080');
        $this->username = env('THINGSBOARD_USERNAME', 'tenant1@thingsboard.org');
        $this->password = env('THINGSBOARD_PASSWORD', 'tenant1');
    }

    public function getToken()
    {
        if (Cache::has('thingsboard_token')) {
            return Cache::get('thingsboard_token');
        }

        $response = Http::withHeaders([
            'accept' => 'application/json',
            'Content-Type' => 'application/json',
        ])
            ->post("{$this->baseUrl}api/auth/login", [
                'username' => $this->username,
                'password' => $this->password,
            ]);


        if ($response->successful()) {
            $token = $response->json('token');
            Cache::put('thingsboard_token', $token, now()->addMinutes(15));
            return $token;
        } else {
            Log::error("ThingsBoard Authentication Failed: " . $response->body());
            throw new Exception('Unable to authenticate with ThingsBoard: ' . $response->body());
        }
    }


    public function createOrUpdateDevice(array $data)
    {

        $token = $this->getToken();

        $payload = [
            'name'       => $data['name'] ?? null,
            'type'       => $data['type'] ?? null,
            'label'      => $data['label'] ?? null,
            'version'    => $data['version'] ?? 1,
            'deviceProfileId' => isset($data['deviceProfileId']['id']) ? $data['deviceProfileId'] : null,
            'customerId' => [
                'id' => $data['customerId'] ?? null,
                'entityType' => 'CUSTOMER'
            ],
            'deviceData' => $data['deviceData'] ?? [],
            'additionalInfo' => $data['additionalInfo'] ?? [],
        ];


        // Optional fields
        if (!empty($data['id'])) {
            $payload['id'] = [
                'id' => $data['id'],
                'entityType' => 'DEVICE'
            ];
        }
        if (!empty($data['firmwareId'])) {
            $payload['firmwareId'] = [
                'id' => $data['firmwareId'],
                'entityType' => 'OTA_PACKAGE'
            ];
        }
        if (!empty($data['softwareId'])) {
            $payload['softwareId'] = [
                'id' => $data['softwareId'],
                'entityType' => 'OTA_PACKAGE'
            ];
        }





        $url = "{$this->baseUrl}api/device";
        $method = 'post';

        $response = Http::withHeaders([
            'Authorization' => "Bearer $token",
            'Accept' => 'application/json',
            'Content-Type' => 'application/json',
        ])->post($url, $payload);

        if (!$response->successful()) {
            Log::error("API Error Response:", ['body' => $response->body()]);
            throw new Exception('API Error: ' . $response->body());
        }

        $apiResponse = $response->json();

        return $apiResponse;
    }



    public function deleteDevice(array $data)
    {
        $token = $this->getToken();


        $url = "{$this->baseUrl}api/device/{$data['deviceId']}";

        $response = Http::withHeaders([
            'Authorization' => "Bearer $token",
            'Accept' => 'application/json',
        ])->delete($url);



        // If response body is empty, assume success
        if ($response->status() === 200 && empty($response->body())) {
            return ['message' => 'Device deleted successfully'];
        }

        if ($response->successful()) {
            return $response->json();
        } else {
            throw new Exception('Failed to create Device: ' . $response->body());
            Log::info('API Response:', ['response' => $response]);
        }

        throw new Exception('Failed to create user: ' . $response->body());
    }
}
