<?php

namespace routes;

use classes\authentication;
use classes\n8n;
use classes\response;
use classes\router;
use objects\logs_o;
use stdClass;
use traits\route_t;

class moduleN8nRoute
{
    use route_t;

    public function run(): void
    {
        global /** @var response $response */
        /** @var router $router */
        $router, $response;

        $this->get('/modules/n8n/workflows', function () {
            global $response;
            self::requirePermission('modules_n8n_workflows_view');
            $user = (new authentication())->get_user();
            if (!$user) {
                $response->error('Invalid session', 400);
            }

            $filters = $this->filterRequestParameters($_GET, [
                'active',
                'tags',
                'name',
                'projectId',
                'excludePinnedData',
                'limit',
                'cursor',
            ]);

            $result = (new n8n())->listWorkflows($filters);
            (new logs_o())->add('modules_n8n', 'global', 1, $user->id, 'MODULES_N8N_WORKFLOWS_LIST', 'Listed n8n workflows');
            $response->success($result, 200);
        }, [
            'modules_n8n_workflows_view' => 'List n8n workflows',
        ]);

        $this->get('/modules/n8n/workflows/{id}', function () {
            global $response;
            self::requirePermission('modules_n8n_workflows_view');
            $user = (new authentication())->get_user();
            if (!$user) {
                $response->error('Invalid session', 400);
            }

            $workflowId = (string)$this->fromRoute('id');
            $result = (new n8n())->getWorkflow($workflowId, $this->toBool($this->fromQuery('excludePinnedData')));
            (new logs_o())->add('modules_n8n', 'global', 1, $user->id, 'MODULES_N8N_WORKFLOW_GET', 'Fetched n8n workflow');
            $response->success($result, 200);
        }, [
            'modules_n8n_workflows_view' => 'Get a specific n8n workflow',
        ]);

        $this->post('/modules/n8n/workflows', function () {
            global $response;
            self::requirePermission('modules_n8n_workflows_manage');
            $user = (new authentication())->get_user();
            if (!$user) {
                $response->error('Invalid session', 400);
            }

            $body = $this->readJsonBody();
            $workflow = $this->extractWorkflowPayload($body);

            $result = (new n8n())->createWorkflow($workflow);
            (new logs_o())->add('modules_n8n', 'global', 1, $user->id, 'MODULES_N8N_WORKFLOW_CREATE', 'Created n8n workflow');
            $response->success($result, 200);
        }, [
            'modules_n8n_workflows_manage' => 'Create n8n workflows',
        ]);

        $this->put('/modules/n8n/workflows/{id}', function () {
            global $response;
            self::requirePermission('modules_n8n_workflows_manage');
            $user = (new authentication())->get_user();
            if (!$user) {
                $response->error('Invalid session', 400);
            }

            $body = $this->readJsonBody();
            $workflow = $this->extractWorkflowPayload($body);

            $result = (new n8n())->updateWorkflow((string)$this->fromRoute('id'), $workflow);
            (new logs_o())->add('modules_n8n', 'global', 1, $user->id, 'MODULES_N8N_WORKFLOW_UPDATE', 'Updated n8n workflow');
            $response->success($result, 200);
        }, [
            'modules_n8n_workflows_manage' => 'Update n8n workflows',
        ]);

        $this->post('/modules/n8n/workflows/{id}/publish', function () {
            global $response;
            self::requirePermission('modules_n8n_workflows_manage');
            $user = (new authentication())->get_user();
            if (!$user) {
                $response->error('Invalid session', 400);
            }

            $body = $this->readJsonBody(false);
            $options = $body !== null ? $this->filterObjectProperties($body, ['versionId', 'name', 'description']) : null;

            $result = (new n8n())->publishWorkflow((string)$this->fromRoute('id'), $options);
            (new logs_o())->add('modules_n8n', 'global', 1, $user->id, 'MODULES_N8N_WORKFLOW_PUBLISH', 'Published n8n workflow');
            $response->success($result, 200);
        }, [
            'modules_n8n_workflows_manage' => 'Publish n8n workflows',
        ]);

        $this->post('/modules/n8n/workflows/{id}/deactivate', function () {
            global $response;
            self::requirePermission('modules_n8n_workflows_manage');
            $user = (new authentication())->get_user();
            if (!$user) {
                $response->error('Invalid session', 400);
            }

            $result = (new n8n())->deactivateWorkflow((string)$this->fromRoute('id'));
            (new logs_o())->add('modules_n8n', 'global', 1, $user->id, 'MODULES_N8N_WORKFLOW_DEACTIVATE', 'Deactivated n8n workflow');
            $response->success($result, 200);
        }, [
            'modules_n8n_workflows_manage' => 'Deactivate n8n workflows',
        ]);

        $this->post('/modules/n8n/webhooks/trigger', function () {
            global $response;
            self::requirePermission('modules_n8n_workflows_run');
            $user = (new authentication())->get_user();
            if (!$user) {
                $response->error('Invalid session', 400);
            }

            $body = $this->readJsonBody();
            $webhookTarget = $this->extractWebhookTarget($body);
            $payload = property_exists($body, 'payload') ? $body->payload : null;
            $query = property_exists($body, 'query') ? $this->objectToArray($body->query) : [];
            $method = $this->normalizeHttpMethod(property_exists($body, 'method') ? (string)$body->method : 'POST');

            $result = (new n8n())->runWebhook($webhookTarget, $payload, $method, $query);
            (new logs_o())->add('modules_n8n', 'global', 1, $user->id, 'MODULES_N8N_WEBHOOK_TRIGGER', 'Triggered n8n webhook');
            $response->success($result, 200);
        }, [
            'modules_n8n_workflows_run' => 'Trigger n8n workflows through webhooks',
        ]);

        $this->get('/modules/n8n/executions', function () {
            global $response;
            self::requirePermission('modules_n8n_executions_view');
            $user = (new authentication())->get_user();
            if (!$user) {
                $response->error('Invalid session', 400);
            }

            $filters = $this->filterRequestParameters($_GET, [
                'includeData',
                'status',
                'workflowId',
                'projectId',
                'limit',
                'cursor',
            ]);

            $result = (new n8n())->listExecutions($filters);
            (new logs_o())->add('modules_n8n', 'global', 1, $user->id, 'MODULES_N8N_EXECUTIONS_LIST', 'Listed n8n executions');
            $response->success($result, 200);
        }, [
            'modules_n8n_executions_view' => 'List n8n executions',
        ]);

        $this->get('/modules/n8n/executions/{id}', function () {
            global $response;
            self::requirePermission('modules_n8n_executions_view');
            $user = (new authentication())->get_user();
            if (!$user) {
                $response->error('Invalid session', 400);
            }

            $result = (new n8n())->getExecution((int)$this->fromRoute('id'), $this->toBool($this->fromQuery('includeData')));
            (new logs_o())->add('modules_n8n', 'global', 1, $user->id, 'MODULES_N8N_EXECUTION_GET', 'Fetched n8n execution');
            $response->success($result, 200);
        }, [
            'modules_n8n_executions_view' => 'Get a specific n8n execution',
        ]);

        $this->post('/modules/n8n/executions/{id}/retry', function () {
            global $response;
            self::requirePermission('modules_n8n_workflows_run');
            $user = (new authentication())->get_user();
            if (!$user) {
                $response->error('Invalid session', 400);
            }

            $body = $this->readJsonBody(false);
            $loadWorkflow = $body !== null && property_exists($body, 'loadWorkflow')
                ? $this->toBool($body->loadWorkflow)
                : false;

            $result = (new n8n())->retryExecution((int)$this->fromRoute('id'), $loadWorkflow);
            (new logs_o())->add('modules_n8n', 'global', 1, $user->id, 'MODULES_N8N_EXECUTION_RETRY', 'Retried n8n execution');
            $response->success($result, 200);
        }, [
            'modules_n8n_workflows_run' => 'Retry n8n executions',
        ]);

        $this->post('/modules/n8n/executions/{id}/stop', function () {
            global $response;
            self::requirePermission('modules_n8n_workflows_manage');
            $user = (new authentication())->get_user();
            if (!$user) {
                $response->error('Invalid session', 400);
            }

            $result = (new n8n())->stopExecution((int)$this->fromRoute('id'));
            (new logs_o())->add('modules_n8n', 'global', 1, $user->id, 'MODULES_N8N_EXECUTION_STOP', 'Stopped n8n execution');
            $response->success($result, 200);
        }, [
            'modules_n8n_workflows_manage' => 'Stop running n8n executions',
        ]);
    }

    private function readJsonBody(bool $required = true): ?object
    {
        global $response;

        $raw = file_get_contents('php://input');
        if ($raw === false || trim($raw) === '') {
            if ($required) {
                $response->error('Request body must contain valid JSON.', 400);
            }

            return null;
        }

        $decoded = json_decode($raw);
        if (json_last_error() !== JSON_ERROR_NONE || !is_object($decoded)) {
            $response->error('Request body must contain valid JSON.', 400);
        }

        return $decoded;
    }

    private function extractWorkflowPayload(object $body): object
    {
        global $response;

        $workflow = property_exists($body, 'workflow') && is_object($body->workflow)
            ? $body->workflow
            : $body;

        if (!property_exists($workflow, 'name') && !property_exists($workflow, 'nodes') && !property_exists($workflow, 'connections')) {
            $response->error('Workflow payload is missing. Provide a workflow object or workflow fields in the request body.', 400);
        }

        return $workflow;
    }

    private function extractWebhookTarget(object $body): string
    {
        global $response;

        foreach (['webhook_url', 'webhookUrl', 'webhook_path', 'webhookPath'] as $field) {
            if (property_exists($body, $field) && is_string($body->{$field}) && trim($body->{$field}) !== '') {
                return trim($body->{$field});
            }
        }

        $response->error('Provide webhook_url or webhook_path to trigger an n8n workflow.', 400);
    }

    private function normalizeHttpMethod(string $method): string
    {
        $normalized = strtoupper(trim($method));
        if (!in_array($normalized, ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'], true)) {
            return 'POST';
        }

        return $normalized;
    }

    private function filterRequestParameters(array $parameters, array $allowedKeys): array
    {
        $allowed = array_flip($allowedKeys);
        $filtered = [];

        foreach ($parameters as $key => $value) {
            if (isset($allowed[$key]) && $value !== '' && $value !== null) {
                $filtered[$key] = $value;
            }
        }

        return $filtered;
    }

    private function filterObjectProperties(object $source, array $allowedKeys): object
    {
        $filtered = new stdClass();

        foreach ($allowedKeys as $key) {
            if (property_exists($source, $key) && $source->{$key} !== null && $source->{$key} !== '') {
                $filtered->{$key} = $source->{$key};
            }
        }

        return $filtered;
    }

    private function objectToArray(mixed $value): array
    {
        if (is_array($value)) {
            return $value;
        }

        if (is_object($value)) {
            $encoded = json_encode($value, JSON_UNESCAPED_UNICODE);
            if ($encoded !== false) {
                $decoded = json_decode($encoded, true);
                if (is_array($decoded)) {
                    return $decoded;
                }
            }
        }

        return [];
    }

    private function toBool(mixed $value): bool
    {
        if (is_bool($value)) {
            return $value;
        }

        if (is_string($value)) {
            $normalized = strtolower(trim($value));
            return in_array($normalized, ['1', 'true', 'yes', 'on'], true);
        }

        if (is_int($value)) {
            return $value === 1;
        }

        return false;
    }
}
