<?php

namespace App\Services;

use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class TextbookCoverStorageService
{
    /**
     * 保存教材封面上传到云存储，返回URL
     */
    public function uploadCover(UploadedFile $file, ?string $textbookId = null): ?string
    {
        // 验证文件类型
        $allowedMimeTypes = ['image/jpeg', 'image/png', 'image/webp'];
        if (!in_array($file->getMimeType(), $allowedMimeTypes)) {
            Log::error('TextbookCoverStorageService: 不支持的文件类型', ['mime_type' => $file->getMimeType()]);
            return null;
        }

        // 验证文件大小（最大 5MB）
        $maxSize = 5 * 1024 * 1024;
        if ($file->getSize() > $maxSize) {
            Log::error('TextbookCoverStorageService: 文件过大', ['size' => $file->getSize()]);
            return null;
        }

        // 生成唯一文件名
        $extension = $file->getClientOriginalExtension();
        $filename = Str::uuid() . '.' . $extension;

        // 构建存储路径
        $directory = $textbookId ? "textbook-covers/{$textbookId}" : 'textbook-covers/temp';
        $path = $directory . '/' . $filename;

        // 获取文件二进制内容
        $binary = file_get_contents($file->getPathname());

        // 使用云存储服务
        $storageService = app(PdfStorageService::class);
        $url = $storageService->put($path, $binary);

        if (!$url) {
            Log::error('TextbookCoverStorageService: 上传失败', ['path' => $path]);
            return null;
        }

        Log::info('TextbookCoverStorageService: 上传成功', [
            'path' => $path,
            'url' => $url,
            'textbook_id' => $textbookId,
        ]);

        return $url;
    }

    /**
     * 删除封面文件
     */
    public function deleteCover(string $url): bool
    {
        // 注意：又拍云和春笋云目前没有删除API
        // 这里只是记录日志，实际删除需要手动或定时任务处理
        Log::warning('TextbookCoverStorageService: 删除操作未实现', ['url' => $url]);
        return true;
    }

    /**
     * 获取存储驱动信息
     */
    public function getStorageInfo(): array
    {
        $driver = config('services.pdf_storage.driver', env('PDF_STORAGE_DRIVER', 'local'));

        return [
            'driver' => $driver,
            'name' => match ($driver) {
                'upyun' => '又拍云',
                'chunsun' => '春笋云',
                'local' => '本地存储',
                default => '未知',
            },
            'supports_delete' => false, // 又拍云和春笋都不支持删除API
        ];
    }
}