<?php

namespace routes;

use classes\db;
use classes\economic;
use classes\release_manager;
use classes\router;
use classes\shelly;
use classes\slack;
use classes\virkdata;
use modules\shelly\helpers\shelly_device_switch;
use modules\shelly\helpers\shelly_request_body_get_states;
use modules\virkdata\helpers\virkdata_response;
use objects\departments_o;
use objects\orders_o;
use objects\product_options_o;
use objects\products_o;
use objects\users_o;
use traits\route_t;

class workerRoute
{
    use route_t;

    public function run(): void
    {
        $this->get('/worker/version', function () {
            global /** @var router $router */
            $response, $router;
            $response->success(['version' => redis->get('worker_target_version') ?? 'unknown'] );
        });
        $this->get('/worker/update-version', function () {
            global /** @var router $router */
            $response, $router;
            self::requirePermission('worker_update_version');
            self::requireParameters(['version']);
            $version = (string)self::getParameter('version');
            redis->set('worker_target_version', $version);
            $response->success(['message' => 'Version update functionality is not yet implemented.']);
        });
        $this->get('/worker/test', function () {
            global $response;
            $response->error('This endpoint is disabled for security reasons.', 403);
        });
        $this->get('/worker/status', function () {
            global /** @var router $router */
            $response, $router, $db, $REDIS_CONFIG, $CONFIG_DB;
            $response->success([
                'message' => 'Worker is running',
                'status' => 'OK',
                'time' => date('Y-m-d H:i:s'),
                'timezone' => date_default_timezone_get(),
                'host' => gethostname(),
                'version' => '1.0.1',
                'api_commit_sha' => release_manager::backendCommitSha(),
                'routes' => $router->countRoutes(),
                'redis' => [
                    'host' => $REDIS_CONFIG['host'],
                    'user' => $REDIS_CONFIG['user'],
                    'database' => $REDIS_CONFIG['database'],
                    'password' => $REDIS_CONFIG['password'] ? '********' : 'NOT_SET',
                    'port' => $REDIS_CONFIG['port'],
                    'status' => (new \classes\redis())->ping() ? 'OK' : 'ERROR',
                ],
                'database' => [
                    'host' => $CONFIG_DB['host'],
                    'database' => $CONFIG_DB['database'],
                    'user' => $CONFIG_DB['user'],
                    'status' => $db->testConnection() ? 'OK' : 'ERROR',
                ],
            ]);
        });
        $this->get('/worker/debug', function () {
            global $response;
            $response->error('This endpoint is disabled for security reasons.', 403);
        });
        $this->get('/worker/debug/on', function () {
            global $response;
            $response->error('This endpoint is disabled for security reasons.', 403);
        });
        $this->get('/worker/debug/off', function () {
            global $response;
            $response->error('This endpoint is disabled for security reasons.', 403);
        });
        $this->get('/worker/licenseplates', function () {
            global $response;
            $response->error('This endpoint is disabled for security reasons.', 403);
        });
        $this->get('/economic/doesCustomerExist', function () {
           global $response;
           self::requirePermission( 'economic_does_customer_exist'); // TODO: Remove this
           self::requireParameters(['cvr']);
           $cvr = self::getParameter('cvr');
           // Check if the customer exists in E-conomic.
            if (!is_numeric($cvr)) {
                $response->error('Invalid CVR number', 400);
            }
            $economic = new economic();
            $results = $economic->customers->customers->search([
                'corporateIdentificationNumber' => (string)$cvr,
            ],[
                'skipPages' => 0,
                'pageSize' => 1000, // Since the limit is 1000, we need to set the page size to 1000.
            ])->collection;
            if (count($results) === 0) {
                $response->error('Customer not found', 404);
            }
           $response->success(['cvr' => $cvr, 'result' => $results], 200);
        });
        $this->get('/cvr/lookup', function () {
            global $response;
            self::requirePermission('cvr_lookup'); // TODO: Remove this
            self::requireParameters(['cvr']);
            $cvr = self::getParameter('cvr');
            if (!is_numeric($cvr)) {
                $response->error('Invalid CVR number', 400);
            }
            // Check if the result is cached
            if (!empty(redis->get('cvr_lookup_' . $cvr))) {
                $result = (new virkdata_response())->populate((array)json_decode(redis->get('cvr_lookup_' . $cvr)));
            } else {
                $virkdata = new virkdata();
                $result = $virkdata->getCompanyInformation($cvr, '', []);
                // Cache the result
                redis->set('cvr_lookup_' . $cvr, json_encode($result->asArray()));
                // Set the cache expiration time (3 days)
                redis->expire('cvr_lookup_' . $cvr, (60 * 60 * 24 * 4));
            }
            $response->success(['cvr' => $cvr, 'result' => (object)$result->asArray(), 'phone' => $result->phone, 'email' => $result->email], 200);
        });
    }

    protected function FORMAT_LICENSE_PLATE(string $plate): string
    {
        // Remove all non-alphanumeric characters
        $cleaned = preg_replace('/[^A-Za-z0-9]/', '', $plate);
        // Convert to uppercase
        return strtoupper($cleaned);
    }
}
