<?php
declare(strict_types=1);

namespace WriteTextAI\WriteTextAI\Model;

use WriteTextAI\WriteTextAI\Api\ImageBase64ApiInterface;
use Magento\Framework\Webapi\Rest\Response as RestResponse;
use Magento\Catalog\Model\ResourceModel\Product\Gallery;
use Magento\Catalog\Model\Product\Media\Config as MediaConfig;
use Psr\Log\LoggerInterface;

/**
 * Class ImageBase64Api
 * Implementation for retrieving image data in base64 format
 */
class ImageBase64Api implements ImageBase64ApiInterface
{
    /**
     * @var RestResponse
     */
    private $response;

    /**
     * @var Gallery
     */
    private $gallery;

    /**
     * @var MediaConfig
     */
    private $mediaConfig;

    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * @param RestResponse $response
     * @param Gallery $gallery
     * @param MediaConfig $mediaConfig
     * @param LoggerInterface $logger
     */
    public function __construct(
        RestResponse $response,
        Gallery $gallery,
        MediaConfig $mediaConfig,
        LoggerInterface $logger
    ) {
        $this->response = $response;
        $this->gallery = $gallery;
        $this->mediaConfig = $mediaConfig;
        $this->logger = $logger;
    }

    /**
     * Get image data in base64 format
     *
     * @param string $imageId
     * @return \Magento\Framework\DataObject
     */
    public function getBase64(string $imageId)
    {
        //get image data
        $imageUrl = $this->getImageUrlViaImageId($imageId);
        $imageData = $this->getBase64Image($imageUrl);
        // Hardcoded JSON response
        $responseData = [
            'id' => '1',
            'data' => $imageData
        ];

        return $this->response->setBody(json_encode($responseData))->sendResponse();
    }

    /**
     * Get image data in base64 format
     *
     * @param string $imageUrl
     * @return string
     */
    public function getBase64Image($imageUrl)
    {
        //@codingStandardsIgnoreStart
        $type = pathinfo($imageUrl, PATHINFO_EXTENSION);
        $data = file_get_contents($imageUrl);
        //@codingStandardsIgnoreEnd
        $base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);

        return $base64;
    }

    /**
     * Fetch image URL by image ID from gallery
     *
     * @param string $imageId
     * @return string|null
     */
    private function getImageUrlViaImageId($imageId)
    {
        try {
            // Load image data from gallery table by value_id
            $imageData = $this->gallery->loadDataFromTableByValueId(
                Gallery::GALLERY_TABLE,
                [(int)$imageId]
            );

            if (empty($imageData) || !isset($imageData[0]['value'])) {
                $this->logger->warning(
                    'Image not found in gallery',
                    ['image_id' => $imageId]
                );
                return null;
            }

            // Get the file path from gallery
            $filePath = $imageData[0]['value'];

            // Build full media URL using Magento's media config
            $imageUrl = $this->mediaConfig->getMediaUrl($filePath);

            return $imageUrl;
        } catch (\Exception $e) {
            $this->logger->error(
                'Error fetching image URL from gallery',
                [
                    'image_id' => $imageId,
                    'error' => $e->getMessage()
                ]
            );
            return null;
        }
    }
}
