<?php

namespace App\Services\Scss;

use App\Models\Products\Product;
use App\Models\Scss\ScssVersion;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

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

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

    /**
     * Obtiene la ruta completa del archivo
     *
     * @param Product $product
     * @param ScssVersion|string $version
     * @param string $filename
     * @return string
     */
    private static function getFilePath(Product $product, $version, string $filename): string
    {
        $directory = self::getDirectoryPath($product, $version);
        // Asegurar que el filename no tenga extensión .scss duplicada
        $filename = Str::endsWith($filename, '.scss') ? Str::before($filename, '.scss') : $filename;
        return $directory . '/' . $filename . '.scss';
    }

    /**
     * Guarda un archivo SCSS en el storage
     *
     * @param Product $product
     * @param ScssVersion|string $version
     * @param string $filename
     * @param string $content
     * @return bool
     */
    public static function saveFile(Product $product, $version, string $filename, string $content): bool
    {
        try {
            $filePath = self::getFilePath($product, $version, $filename);
            $directory = self::getDirectoryPath($product, $version);

            // 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: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Lee un archivo SCSS del storage
     *
     * @param Product $product
     * @param ScssVersion|string $version
     * @param string $filename
     * @return string|null
     */
    public static function getFile(Product $product, $version, string $filename): ?string
    {
        try {
            $filePath = self::getFilePath($product, $version, $filename);

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

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

    /**
     * Elimina un archivo SCSS del storage
     *
     * @param Product $product
     * @param ScssVersion|string $version
     * @param string $filename
     * @return bool
     */
    public static function deleteFile(Product $product, $version, string $filename): bool
    {
        try {
            $filePath = self::getFilePath($product, $version, $filename);

            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: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Lista todos los archivos de una versión
     *
     * @param Product $product
     * @param ScssVersion|string $version
     * @return array Array de nombres de archivos (sin extensión)
     */
    public static function getAllFiles(Product $product, $version): array
    {
        try {
            $directory = self::getDirectoryPath($product, $version);

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

            $files = Storage::files($directory);
            $filenames = [];

            foreach ($files as $file) {
                $basename = basename($file);
                // Remover extensión .scss
                $filename = Str::endsWith($basename, '.scss')
                    ? Str::before($basename, '.scss')
                    : $basename;
                $filenames[] = $filename;
            }

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

    /**
     * Verifica si existe un archivo
     *
     * @param Product $product
     * @param ScssVersion|string $version
     * @param string $filename
     * @return bool
     */
    public static function fileExists(Product $product, $version, string $filename): bool
    {
        try {
            $filePath = self::getFilePath($product, $version, $filename);
            return Storage::exists($filePath);
        } catch (\Exception $e) {
            \Log::error('Error al verificar archivo SCSS: ' . $e->getMessage());
            return false;
        }
    }
}
