<?php

namespace App\Services;

use App\Models\TimeseriesKeyMaster;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Exception;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Cache;
use Carbon\Carbon;


class RuleChainService
{
    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 getRuleChains($page, $pageSize)
    {
        try {
            $token = $this->getToken();

            $response = Http::withHeaders([
                'accept' => 'application/json',
                'Content-Type' => 'application/json',
                'X-Authorization' => "Bearer {$token}",
            ])->get("{$this->baseUrl}api/ruleChains", [
                'page' => $page,
                'pageSize' => $pageSize,
                'sortProperty' => 'createdTime',
                'sortOrder' => 'DESC'
            ]);

            if ($response->successful()) {
                return $response->json();
            } else {
                Log::error("Failed to fetch rule chains: " . $response->body());
                throw new Exception('Failed to fetch rule chains: ' . $response->body());
            }

        } catch (Exception $e) {
            Log::error("Error: " . $e->getMessage());
            throw new Exception('Error while fetching rule chains: ' . $e->getMessage());
        }
    }

    public function exportRuleChains($limit)
    {
        try {
            $token = $this->getToken();

            // Make the export API request
            $response = Http::withHeaders([
                'accept' => 'application/json',
                'Content-Type' => 'application/json',
                'X-Authorization' => "Bearer {$token}",
            ])->get("{$this->baseUrl}api/ruleChains/export", [
                'limit' => $limit
            ]);

            if ($response->successful()) {
                return $response->json();
            } else {
                Log::error("Failed to export rule chains: " . $response->body());
                throw new Exception('Failed to export rule chains: ' . $response->body());
            }

        } catch (Exception $e) {
            Log::error("Error exporting rule chains: " . $e->getMessage());
            throw new Exception('Error exporting rule chains: ' . $e->getMessage());
        }
    }

    public function getRuleChainById($ruleChainId)
    {
        try {
            $token = $this->getToken();

            $response = Http::withHeaders([
                'accept' => 'application/json',
                'Content-Type' => 'application/json',
                'X-Authorization' => "Bearer {$token}",
            ])->get("{$this->baseUrl}api/ruleChain/{$ruleChainId}");

            if ($response->successful()) {
                return $response->json();
            } else {
                Log::error("Failed to fetch rule chain: " . $response->body());
                throw new Exception('Failed to fetch rule chain: ' . $response->body());
            }

        } catch (Exception $e) {
            Log::error("Error fetching rule chain: " . $e->getMessage());
            throw new Exception('Error fetching rule chain: ' . $e->getMessage());
        }
    }
}
