<?php

namespace App\Modules\LodgingPlace\Domain;

use Illuminate\Support\Facades\Http;

final class LodgingPlaceIconManager
{
    private string $iconFolder;
    private string $iconPublicBaseUrl;
    public function __construct()
    {
        $this->iconFolder = config('var.PATH_PRIVATE') . 'image/lodging_place/icon';

        $this->iconPublicBaseUrl = config('var.PATH_PUBLIC') . 'image/lodging_place/icon';
    }

    public function ensureIconExists(string $iconUrl): void
    {
        $iconName = basename(parse_url($iconUrl, PHP_URL_PATH));
        $fullPath = $this->iconFolder . '/' . $iconName;
        // dd($fullPath);
        if (!file_exists($fullPath)) {
            $response = Http::get($iconUrl);
            if ($response->successful()) {
                // Asegurar que la carpeta exista
                if (!is_dir(dirname($fullPath))) {
                    mkdir(dirname($fullPath), 0775, true);
                }
                file_put_contents($fullPath, $response->body());
            } else {
                throw new \RuntimeException("No se pudo descargar el ícono desde: {$iconUrl}");
            }
        }
    }
    public function getPublicUrl(string $iconUrl): string
    {
        $iconName = basename(parse_url($iconUrl, PHP_URL_PATH));
        // dd($this->iconPublicBaseUrl . $iconName);
        $urlRelative = 'image/lodging_place/icon/';
        return $urlRelative . $iconName;
    }
}
