<?php
/**
 * @package     MefisAssetBridge
 * @subpackage  Joomla_Administrator_Component
 *
 * @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 Mefi\Component\MefisAssetBridge\Administrator\Traits\CoreBridge;

defined('_JEXEC') or die;

use Joomla\CMS\Uri\Uri;
use Joomla\CMS\Language\Text;
use MefisAssetBridgeCore\Api\Response\ApiResponse;

trait AssetTrait
{
    /**
     * Fetch assets from Mefi's Asset Bridge server
     *
     * @param array $params Parameters for fetching assets (e.g., filters, pagination)
     *
     * @return Array of assets data
     */
    protected function coreGetAsset($params): array
    {
        /** This is no longer in use, switch to coreGetAssetData instead **/
        return [];
        $apiFactory = $this->getApiFactory();

        $assetsEndpoint = $apiFactory->createEndpoint('getAsset');
        $response = $assetsEndpoint->sendRequest($params);

        if (! $response->isSuccess()) {
            throw new \RuntimeException($response->getMessage() ?: Text::_('COM_MEFISASSETBRIDGE_GET_ASSET_FAILED', 'Failed to fetch asset, please try again.'));
        }

        $asset = $response->getData();
        if(!isset($asset['data']) || !isset($asset['asset_id'])) {
            throw new \RuntimeException(Text::_('COM_MEFISASSETBRIDGE_GET_ASSET_INVALID_RESPONSE', 'Invalid asset data received from server.'));
        }

        return $asset;
    }

    protected function coreGetAssetData($id, $params = []): array
    {
        $apiFactory     = $this->getApiFactory();
        $assetsEndpoint = $apiFactory->createEndpoint('getAssetData');

        $response = $assetsEndpoint->sendRequest(array_merge(['id' => $id], $params));

        if (!$response->isSuccess()) {
            throw new \RuntimeException($response->getMessage() ?: Text::_('COM_MEFISASSETBRIDGE_GET_ASSET_DATA_FAILED'));
        }

        return $response->getData();
    }

    protected function coreDeleteAsset($id): array
    {

        $apiFactory = $this->getApiFactory();

        $assetsEndpoint = $apiFactory->createEndpoint('deleteAsset');
        $response = $assetsEndpoint->sendRequest(['asset_id' => $id]);

        if (! $response->isSuccess()) {
            throw new \RuntimeException($response->getMessage() ?: Text::_('COM_MEFISASSETBRIDGE_DELETE_ASSET_FAILED', 'Failed to delete asset, please try again.'));
        }

        return $response->getData();
    }

    protected function coreGetAssets($params): array
    {

        $apiFactory = $this->getApiFactory();

        $assetsEndpoint = $apiFactory->createEndpoint('getAssets');
        $response = $assetsEndpoint->sendRequest($params);

        if (! $response->isSuccess()) {
            throw new \RuntimeException($response->getMessage() ?: Text::_('COM_MEFISASSETBRIDGE_GET_ASSETS_FAILED', 'Failed to fetch assets, please try again.'));
        }

        return $response->getData();
    }

    protected function coreGetAssetThumbnail($id, $params = []): array
    {
        $apiFactory     = $this->getApiFactory();
        $assetsEndpoint = $apiFactory->createEndpoint('getAssetThumbnail');

        $response = $assetsEndpoint->sendRequest(array_merge(['id' => $id], $params));

        if (!$response->isSuccess()) {
            throw new \RuntimeException($response->getMessage() ?: Text::_('COM_MEFISASSETBRIDGE_GET_ASSET_THUMBNAIL_FAILED'));
        }

        return $response->getData();
    }
    protected function coreSaveAsset($params): array
    {
        $apiFactory = $this->getApiFactory();

        if (!isset($params['element']) || !isset($params['id'])) {
            throw new \RuntimeException(Text::_('COM_MEFISASSETBRIDGE_SAVE_ASSET_MISSING_PARAMS'));
        }

        $params['element']['name']     = $params['element']['name']     ?? 'Unnamed Asset';
        $params['element']['modified'] = $params['element']['modified'] ?? date('Y-m-d\TH:i:s\Z', time());

        $payload = [
            'yootheme_id' => $params['id'],
            'data'        => $params['element'],
            'name'        => $params['element']['name'],
            'modified'    => $params['element']['modified'],
            'asset_type'  => $params['element']['type']    ?? 'layout',
            'version'     => $params['element']['version'] ?? '0.0.0',
            'domain'      => Uri::getInstance()->getHost(),
            'cms_type'    => 'Joomla!',
            'cms_version' => JVERSION,
            'category'    => $params['category']  ?? [],
            'thumbnail'   => $params['thumbnail'],
            'userUuid'    => $params['userUuid']   ?? '',
        ];

        $assetsEndpoint = $apiFactory->createEndpoint('saveAsset');
        $response       = $assetsEndpoint->sendRequest($payload);

        if (!$response->isSuccess()) {
            throw new \RuntimeException($response->getMessage() ?: Text::_('COM_MEFISASSETBRIDGE_SAVE_ASSET_FAILED'));
        }

        return $response->getData();
    }

    protected function coreChangeAssetCategory($params): array
    {
        $apiFactory = $this->getApiFactory();
        if(!isset($params['id']) || !isset($params['category'])) {
            throw new \RuntimeException(Text::_('COM_MEFISASSETBRIDGE_CHANGE_ASSET_CATEGORY_MISSING_PARAMS', 'Missing required parameters to change asset category.'));
        }
        $assetsEndpoint = $apiFactory->createEndpoint('changeAssetCategory');
        $response = $assetsEndpoint->sendRequest([
            'id' => $params['id'],
            'category' => $params['category']
        ]);
        if (! $response->isSuccess()) {
            throw new \RuntimeException($response->getMessage() ?: Text::_('COM_MEFISASSETBRIDGE_CHANGE_ASSET_CATEGORY_FAILED', 'Failed to change asset category, please try again.'));
        }
        return $response->getData();
    }

    protected function coreChangeAssetThumbnail($params): array
    {
        $apiFactory = $this->getApiFactory();
        if (!isset($params['id']) || !isset($params['thumbnail'])) {
            throw new \RuntimeException(Text::_('COM_MEFISASSETBRIDGE_CHANGE_ASSET_THUMBNAIL_MISSING_PARAMS'));
        }
        $assetsEndpoint = $apiFactory->createEndpoint('changeAssetThumbnail');
        $response       = $assetsEndpoint->sendRequest([
            'id'        => $params['id'],
            'thumbnail' => $params['thumbnail'],
            'domain'    => Uri::getInstance()->getHost(),
            'userUuid'  => $params['userUuid']  ?? '',
            'assetUuid' => $params['assetUuid'] ?? '',
        ]);
        if (!$response->isSuccess()) {
            throw new \RuntimeException($response->getMessage() ?: Text::_('COM_MEFISASSETBRIDGE_CHANGE_ASSET_THUMBNAIL_FAILED'));
        }
        return $response->getData();
    }
    protected function coreRenameAsset($id, $newName): array
    {

        $apiFactory = $this->getApiFactory();

        $assetsEndpoint = $apiFactory->createEndpoint('renameAsset');
        $response = $assetsEndpoint->sendRequest(['id' => $id, 'name' => $newName]);

        if (! $response->isSuccess()) {
            throw new \RuntimeException($response->getMessage() ?: Text::_('COM_MEFISASSETBRIDGE_RENAME_ASSET_FAILED', 'Failed to rename asset, please try again.'));
        }

        return $response->getData();
    }
}