<?php
/**
 * @package     MefisAssetBridge
 * @subpackage  MefisAssetBridgeCore_Api_Endpoints
 *
 * @copyright   Copyright (C) 2025 Goran Usljebrka. All rights reserved.
 * @license     Proprietary — No resale or incorporation into other projects without explicit written permission. see LICENSE.txt
 */

namespace MefisAssetBridgeCore\Api\Endpoints\Asset;

use MefisAssetBridgeCore\Api\ApiClient;
use MefisAssetBridgeCore\DTO\ThumbnailDto;
use MefisAssetBridgeCore\Traits\Encryptor;
use MefisAssetBridgeCore\Auth\AuthenticatedUser;
use MefisAssetBridgeCore\Api\Response\ApiResponse;
use MefisAssetBridgeCore\Interfaces\EndpointInterface;

/**
 * changeAssetCategory API Endpoint
 */
class ChangeAssetCategory implements EndpointInterface
{
    use Encryptor;

    /** @var ApiClient API client instance */
    private ApiClient $ApiClient;

    /** @var AuthenticatedUser|null Authenticated user */
    private ?AuthenticatedUser $user;

    private string $uuid;
    private string $pathHash;
    private string $_masterKey;
    /** @var array Required parameters */
    private array $requiredParams = [
        'id',
        'category',
    ];

    private string $validationError = '';

    public function __construct(string $uuid, ApiClient $ApiClient, ?AuthenticatedUser $user, string $pathHash = '', string $masterKey = '')
    {
        $this->ApiClient = $ApiClient;
        $this->user      = $user;
        $this->uuid      = $uuid;
        $this->pathHash  = $pathHash;

    }

    /**
     * Validate request parameters
     *
     * @param array $params Request parameters
     * @return bool True if parameters are valid
     */
    public function validateParams(array $params): bool
    {

        foreach ($this->requiredParams as $param) {
            if (! isset($params[$param])) {
                $this->validationError = sprintf('Missing required parameter: %s', $param);
                return false;
            }
        }

        if(!is_array($params['category'])) {
            $this->validationError = 'Category must be an array';
            return false;
        }

        return true;
    }

    /**
     * Send request to save a asset
     *
     * @param array $params Request parameters
     * @return ApiResponse
     */
    public function sendRequest(array $params): ApiResponse
    {

        // Validate required parameters
        if (! $this->validateParams($params)) {
            return ApiResponse::error($this->validationError);
        }

        $this->ApiClient->setUser($this->user);

        // handle saving category
        if (!empty($params['category'])) {
            // if id exist this is existing category
            if (!empty($params['category']['id'])) {
                $requestData['category_id'] = intval($params['category']['id']);

            } else {
                // no id but we have value
                if (!empty($params['category']['value'])) {
                    $requestData['category_name'] = trim($params['category']['value']);
                }
            }
        }

        if(empty($requestData['category_id']) && empty($requestData['category_name'])) {
            throw new \RuntimeException('Category is missing or invalid.');
        }

        return $this->ApiClient->patch('assets/'.$params['id'].'/category', $requestData);
    }

}
