<?php

namespace App\Services\ScssCdn;

use App\Models\Products\Product;
use App\Models\ScssCdn\ScssCdnBundle;
use Illuminate\Support\Facades\Storage;

class ScssCdnStorageService
{
    /**
     * Ruta base para almacenar archivos SCSS CDN
     */
    private const BASE_PATH = 'SCSS_CDN';

    /**
     * Obtiene la ruta del directorio para un producto y bundle
     *
     * @param Product $product
     * @param ScssCdnBundle|string $bundle
     * @return string
     */
    private static function getDirectoryPath(Product $product, $bundle): string
    {
        $versionString = $bundle instanceof ScssCdnBundle ? $bundle->version : $bundle;
        return self::BASE_PATH . '/' . $product->slug . '/' . $versionString;
    }

    /**
     * Obtiene la ruta completa del archivo respetando estructura de carpetas
     *
     * @param Product $product
     * @param ScssCdnBundle|string $bundle
     * @param string $relativePath Ruta relativa desde la raíz del ZIP
     * @return string
     */
    private static function getFilePath(Product $product, $bundle, string $relativePath): string
    {
        $directory = self::getDirectoryPath($product, $bundle);
        // Normalizar separadores de ruta
        $relativePath = str_replace('\\', '/', $relativePath);
        // Asegurar que no empiece con /
        $relativePath = ltrim($relativePath, '/');
        
        return $directory . '/' . $relativePath;
    }

    /**
     * Guarda un archivo SCSS en el storage respetando estructura de carpetas
     *
     * @param Product $product
     * @param ScssCdnBundle|string $bundle
     * @param string $relativePath Ruta relativa desde la raíz del ZIP
     * @param string $content
     * @return bool
     */
    public static function saveFile(Product $product, $bundle, string $relativePath, string $content): bool
    {
        try {
            $filePath = self::getFilePath($product, $bundle, $relativePath);
            $directory = dirname($filePath);

            // Crear directorio si no existe
            if (!Storage::exists($directory)) {
                Storage::makeDirectory($directory);
            }

            // Guardar archivo
            return Storage::put($filePath, $content) !== false;
        } catch (\Exception $e) {
            \Log::error('Error al guardar archivo SCSS CDN: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Lee un archivo SCSS del storage
     *
     * @param Product $product
     * @param ScssCdnBundle|string $bundle
     * @param string $relativePath Ruta relativa desde la raíz del ZIP
     * @return string|null
     */
    public static function getFile(Product $product, $bundle, string $relativePath): ?string
    {
        try {
            $filePath = self::getFilePath($product, $bundle, $relativePath);

            if (!Storage::exists($filePath)) {
                return null;
            }

            return Storage::get($filePath);
        } catch (\Exception $e) {
            \Log::error('Error al leer archivo SCSS CDN: ' . $e->getMessage());
            return null;
        }
    }

    /**
     * Elimina un archivo SCSS del storage
     *
     * @param Product $product
     * @param ScssCdnBundle|string $bundle
     * @param string $relativePath Ruta relativa desde la raíz del ZIP
     * @return bool
     */
    public static function deleteFile(Product $product, $bundle, string $relativePath): bool
    {
        try {
            $filePath = self::getFilePath($product, $bundle, $relativePath);

            if (!Storage::exists($filePath)) {
                return true; // Ya no existe, consideramos éxito
            }

            return Storage::delete($filePath);
        } catch (\Exception $e) {
            \Log::error('Error al eliminar archivo SCSS CDN: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Lista todos los archivos de un bundle manteniendo estructura
     *
     * @param Product $product
     * @param ScssCdnBundle|string $bundle
     * @return array Array con estructura de archivos ['relative_path' => 'content', ...]
     */
    public static function listFiles(Product $product, $bundle): array
    {
        try {
            $directory = self::getDirectoryPath($product, $bundle);

            if (!Storage::exists($directory)) {
                return [];
            }

            $files = Storage::allFiles($directory);
            $result = [];

            foreach ($files as $file) {
                // Obtener ruta relativa desde el directorio del bundle
                $relativePath = str_replace($directory . '/', '', $file);
                $content = Storage::get($file);
                $result[$relativePath] = $content;
            }

            return $result;
        } catch (\Exception $e) {
            \Log::error('Error al listar archivos SCSS CDN: ' . $e->getMessage());
            return [];
        }
    }

    /**
     * Verifica si existe un archivo
     *
     * @param Product $product
     * @param ScssCdnBundle|string $bundle
     * @param string $relativePath Ruta relativa desde la raíz del ZIP
     * @return bool
     */
    public static function fileExists(Product $product, $bundle, string $relativePath): bool
    {
        try {
            $filePath = self::getFilePath($product, $bundle, $relativePath);
            return Storage::exists($filePath);
        } catch (\Exception $e) {
            \Log::error('Error al verificar archivo SCSS CDN: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Elimina todos los archivos de un bundle
     *
     * @param Product $product
     * @param ScssCdnBundle|string $bundle
     * @return bool
     */
    public static function deleteBundle(Product $product, $bundle): bool
    {
        try {
            $directory = self::getDirectoryPath($product, $bundle);

            if (!Storage::exists($directory)) {
                return true; // Ya no existe, consideramos éxito
            }

            return Storage::deleteDirectory($directory);
        } catch (\Exception $e) {
            \Log::error('Error al eliminar bundle SCSS CDN: ' . $e->getMessage());
            return false;
        }
    }
}

