<?php

namespace Modules\Bms\Services\Adapters\Media;

use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Modules\Bms\Services\Contracts\MediaServiceContract;

/**
 * Media adapter built on Laravel's filesystem. The SmartStorage module
 * transparently swaps the underlying disk (local/S3/Dropbox/GoogleDrive) and
 * adds at-rest encryption, so this adapter never needs to know which backend
 * is active — it just uses the configured/default disk.
 */
class SmartStorageMediaService implements MediaServiceContract
{
    public function store(int $businessId, string $directory, $file, array $options = []): array
    {
        $disk = $options['disk'] ?? config('filesystems.default', 'public');
        $directory = trim($directory, '/');
        $folder = "bms/{$businessId}/{$directory}";

        if (is_string($file)) {
            // A pre-existing local path being adopted into the media library.
            $filename = $options['filename'] ?? Str::random(20) . '_' . basename($file);
            $path = Storage::disk($disk)->putFileAs($folder, $file, $filename);
        } else {
            $filename = $options['filename'] ?? Str::random(20) . '.' . $file->getClientOriginalExtension();
            $path = $file->storeAs($folder, $filename, ['disk' => $disk]);
        }

        return [
            'disk' => $disk,
            'path' => $path,
            'url'  => $this->url($disk, $path),
        ];
    }

    public function url(?string $disk, ?string $path, ?string $fallbackUrl = null): ?string
    {
        if (empty($path)) {
            return $fallbackUrl;
        }

        $disk = $disk ?: config('filesystems.default', 'public');

        try {
            return Storage::disk($disk)->url($path);
        } catch (\Throwable $e) {
            return $fallbackUrl ?? asset('storage/' . ltrim($path, '/'));
        }
    }

    public function delete(?string $disk, ?string $path): bool
    {
        if (empty($path)) {
            return false;
        }

        $disk = $disk ?: config('filesystems.default', 'public');

        try {
            return Storage::disk($disk)->delete($path);
        } catch (\Throwable $e) {
            return false;
        }
    }
}
