<?php

namespace limble\classes;
require_once WD . '/modules/limble/interfaces/limble_endpoints_i.php';
require_once WD . '/modules/limble/classes/limble_request.php';

use Exception;
use limble\helpers\limble_tasks_pagination;
use limble_endpoints_i;

abstract class limble_endpoints extends limble_request implements limble_endpoints_i
{

    /**
     * @inheritDoc
     * @throws Exception If the module is not enabled
     */
    public function listTasks(limble_tasks_pagination $pagination): array
    {
        $this->requireModuleEnabled();
        $url = $this->config->api_url . '/tasks';
        $params = [...$pagination->getParams()];
        return $this->sendRequest(
            $url,
            'GET',
            $params,
            [self::getAuthHeader(), 'Content-Type: application/json']
        );
    }

    /**
     * @inheritDoc
     */
    public function getAuthHeader(): string
    {
        $this->requireModuleEnabled();
        $client_id = $this->config->client_id->getVariableValue();
        $client_secret = $this->config->client_secret->getVariableValue();
        if (empty($client_id)) {
            throw new Exception('Client ID is not set');
        }
        if (empty($client_secret)) {
            throw new Exception('Client Secret is not set');
        }
        // Generate the Basic Auth header
        return $this->generateBasicAuthHeader(
            (string)$client_id,
            (string)$client_secret
        );
    }

    /**
     * @inheritDoc
     * @throws Exception If the module is not enabled
     */
    public function getTaskInstructions(int $taskId): array
    {
        $this->requireModuleEnabled();
        $url = $this->config->api_url . '/tasks/' . $taskId . '/instructions';
        return $this->sendRequest(
            $url,
            'GET',
            [],
            [self::getAuthHeader(), 'Content-Type: application/json']
        );
    }

    /**
     * @inheritDoc
     * @throws Exception If the module is not enabled
     */
    public function getTask(int $taskId): array
    {
        $this->requireModuleEnabled();
        $url = $this->config->api_url . '/tasks';
        // Set the taskId as a pagination parameter
        $pagination = new limble_tasks_pagination();
        $pagination->tasks = $taskId;
        $pagination->limit = 1; // Limit to 1 task
        return $this->sendRequest(
            $url,
            'GET',
            [...$pagination->getParams()],
            [self::getAuthHeader(), 'Content-Type: application/json']
        );
    }
}