<?php

declare(strict_types=1);

namespace SmsNotifier\Service;

use Aws\S3\S3Client;
use Aws\Exception\AwsException;
use Ubnt\UcrmPluginSdk\Service\PluginConfigManager;

class MinioStorageService
{
    /**
     * @var S3Client
     */
    private $s3Client;

    /**
     * @var string
     */
    private $bucket;

    /**
     * @var string
     */
    private $publicUrl;

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

    public function __construct(Logger $logger)
    {
        $this->logger = $logger;
        $this->initializeClient();
    }

    private function initializeClient(): void
    {
        $config = PluginConfigManager::create()->loadConfig();

        $endpoint = $config['minioEndpoint'] ?? 'http://localhost:9002';
        $key = $config['minioAccessKey'] ?? 'minioadmin';
        $secret = $config['minioSecretKey'] ?? 'minioadmin';
        $this->bucket = $config['minioBucket'] ?? 'vouchers-oxxo';
        $this->publicUrl = rtrim($config['minioPublicUrl'] ?? 'http://localhost:9002', '/');

        try {
            $this->s3Client = new S3Client([
                'version' => 'latest',
                'region'  => 'us-east-1', // MinIO doesn't really care about region, but SDK requires it
                'endpoint' => $endpoint,
                'use_path_style_endpoint' => true,
                'credentials' => [
                    'key'    => $key,
                    'secret' => $secret,
                ],
            ]);
        } catch (\Exception $e) {
            $this->logger->error("Error initializing S3 Client: " . $e->getMessage());
        }
    }

    public function uploadFile(string $sourcePath, string $filename): string
    {
        if (!$this->s3Client) {
            $this->logger->error("S3 Client not initialized. Cannot upload.");
            return '';
        }

        try {
            $result = $this->s3Client->putObject([
                'Bucket' => $this->bucket,
                'Key'    => $filename,
                'SourceFile' => $sourcePath,
            ]);
            
            // Construct Public URL
            // We do NOT use $result['ObjectURL'] because that might point to the internal container IP/Port
            // We specifically want to use the public domain provided in config.
            $finalUrl = $this->publicUrl . '/' . $this->bucket . '/' . $filename;
            
            $this->logger->info("Archivo subido exitosamente a MinIO: $finalUrl");
            return $finalUrl;

        } catch (AwsException $e) {
            $this->logger->error("AWS S3 Error uploading file $filename: " . $e->getMessage());
            return '';
        } catch (\Exception $e) {
            $this->logger->error("General Error uploading file $filename: " . $e->getMessage());
            return '';
        }
    }
}
