<?php

namespace BitApps\PiPro\src\Integrations\Flowlu;

use BitApps\Pi\Deps\BitApps\WPKit\Helpers\JSON;
use BitApps\Pi\Helpers\MixInputHandler;
use BitApps\Pi\src\Flow\NodeInfoProvider;

if (!\defined('ABSPATH')) {
    exit;
}

final class FlowluTaskService
{
    private object $http;

    private string $baseUrl;

    private NodeInfoProvider $nodeInfoProvider;

    /**
     * FlowluTaskService constructor.
     */
    public function __construct(object $httpClient, string $baseUrl, NodeInfoProvider $nodeInfoProvider)
    {
        $this->http = $httpClient;
        $this->baseUrl = $baseUrl;
        $this->nodeInfoProvider = $nodeInfoProvider;
    }

    /**
     * Create Flowlu task.
     *
     * @return array
     */
    public function createTask()
    {
        $taskId = $this->nodeInfoProvider->getFieldMapConfigs('task-id.value');
        $taskName = MixInputHandler::replaceMixTagValue($this->nodeInfoProvider->getFieldMapConfigs('task-name.value'));
        $taskDescription = MixInputHandler::replaceMixTagValue($this->nodeInfoProvider->getFieldMapConfigs('task-description.value'));
        $taskDueDate = MixInputHandler::replaceMixTagValue($this->nodeInfoProvider->getFieldMapConfigs('task-due-date.value'));

        $taskData = [];
        if (!empty($taskId)) {
            $taskData['parent_id'] = $taskId;
        }
        if (!empty($taskName)) {
            $taskData['name'] = $taskName;
        }
        if (!empty($taskDescription)) {
            $taskData['description'] = $taskDescription;
        }
        if (!empty($taskDueDate)) {
            $taskData['deadline'] = $taskDueDate;
        }

        try {
            $response = $this->http->request(
                $this->baseUrl . '/module/task/tasks/create',
                'POST',
                JSON::encode($taskData),
                []
            );

            $responseCode = $this->http->getResponseCode();
            $success = $responseCode >= 200 && $responseCode < 300;

            return [
                'response'    => $response,
                'payload'     => $taskData,
                'status_code' => $responseCode,
                'success'     => $success
            ];
        } catch (\Exception $e) {
            return [
                'response'    => [
                    'success' => false,
                    'message' => 'Failed to create task: ' . $e->getMessage()
                ],
                'payload'     => $taskData,
                'status_code' => 500,
                'success'     => false
            ];
        }
    }

    public function updateTask()
    {
        $taskId = MixInputHandler::replaceMixTagValue($this->nodeInfoProvider->getFieldMapConfigs('task-id.value'));
        $parentTaskId = $this->nodeInfoProvider->getFieldMapConfigs('parent-task-id.value');
        $taskName = MixInputHandler::replaceMixTagValue($this->nodeInfoProvider->getFieldMapConfigs('task-name.value'));
        $taskDescription = MixInputHandler::replaceMixTagValue($this->nodeInfoProvider->getFieldMapConfigs('task-description.value'));
        $taskDueDate = MixInputHandler::replaceMixTagValue($this->nodeInfoProvider->getFieldMapConfigs('task-due-date.value'));

        if (empty($taskId)) {
            return [
                'response'    => [
                    'success' => false,
                    'message' => 'Task ID is required for update operation'
                ],
                'payload'     => [],
                'status_code' => 400,
                'success'     => false
            ];
        }
        $taskData = [];
        if (!empty($parentTaskId)) {
            $taskData['parent_id'] = $parentTaskId;
        }
        if (!empty($taskName)) {
            $taskData['name'] = $taskName;
        }
        if (!empty($taskDescription)) {
            $taskData['description'] = $taskDescription;
        }
        if (!empty($taskDueDate)) {
            $taskData['deadline'] = $taskDueDate;
        }

        try {
            $response = $this->http->request(
                $this->baseUrl . "/module/task/tasks/update/{$taskId}",
                'POST',
                JSON::encode($taskData),
                []
            );

            $responseCode = $this->http->getResponseCode();
            $success = $responseCode >= 200 && $responseCode < 300;

            return [
                'response'    => $response,
                'payload'     => $taskData,
                'status_code' => $responseCode,
                'success'     => $success
            ];
        } catch (\Exception $e) {
            return [
                'response'    => [
                    'success' => false,
                    'message' => 'Failed to update task: ' . $e->getMessage()
                ],
                'payload'     => $taskData,
                'status_code' => 500,
                'success'     => false
            ];
        }
    }

    public function getTask()
    {
        $taskId = MixInputHandler::replaceMixTagValue($this->nodeInfoProvider->getFieldMapConfigs('task-id.value'));

        if (empty($taskId)) {
            return [
                'response'    => [
                    'success' => false,
                    'message' => 'Task ID is required for get operation'
                ],
                'payload'     => [],
                'status_code' => 400,
                'success'     => false
            ];
        }
        try {
            $response = $this->http->request(
                $this->baseUrl . "/module/task/tasks/get/{$taskId}",
                'GET',
                [],
                []
            );

            $responseCode = $this->http->getResponseCode();
            $success = $responseCode >= 200 && $responseCode < 300;

            return [
                'response'    => $response,
                'payload'     => ['task_id' => $taskId],
                'status_code' => $responseCode,
                'success'     => $success
            ];
        } catch (\Exception $e) {
            return [
                'response'    => [
                    'success' => false,
                    'message' => 'Failed to get task: ' . $e->getMessage()
                ],
                'payload'     => ['task_id' => $taskId],
                'status_code' => 500,
                'success'     => false
            ];
        }
    }

    public function listTasks()
    {
        try {
            $response = $this->http->request(
                $this->baseUrl . '/module/task/tasks/list',
                'GET',
                [],
                []
            );

            $responseCode = $this->http->getResponseCode();
            $success = $responseCode >= 200 && $responseCode < 300;

            return [
                'response'    => $response,
                'payload'     => [],
                'status_code' => $responseCode,
                'success'     => $success
            ];
        } catch (\Exception $e) {
            return [
                'response'    => [
                    'success' => false,
                    'message' => 'Failed to list tasks: ' . $e->getMessage()
                ],
                'payload'     => [],
                'status_code' => 500,
                'success'     => false
            ];
        }
    }

    public function deleteTask()
    {
        $taskId = MixInputHandler::replaceMixTagValue($this->nodeInfoProvider->getFieldMapConfigs('task-id.value'));
        if (empty($taskId)) {
            return [
                'response'    => [
                    'success' => false,
                    'message' => 'Task ID is required for delete operation'
                ],
                'payload'     => [],
                'status_code' => 400,
                'success'     => false
            ];
        }

        try {
            $response = $this->http->request(
                $this->baseUrl . "/module/task/tasks/delete/{$taskId}",
                'Get',
                [],
                []
            );

            $responseCode = $this->http->getResponseCode();
            $success = $responseCode >= 200 && $responseCode < 300;

            return [
                'response'    => $response,
                'payload'     => ['task_id' => $taskId],
                'status_code' => $responseCode,
                'success'     => $success
            ];
        } catch (\Exception $e) {
            return [
                'response'    => [
                    'success' => false,
                    'message' => 'Failed to delete task: ' . $e->getMessage()
                ],
                'payload'     => ['task_id' => $taskId],
                'status_code' => 500,
                'success'     => false
            ];
        }
    }
}
