<?php

namespace App\Services;

use App\Models\Document;
use App\Models\DownloadLog;
use App\Models\User;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\StreamedResponse;

class DocumentService
{
    /**
     * 验证用户是否有权访问指定文档
     */
    public function validateDocumentAccess(Document $document, User $user): bool
    {
        return true;
    }

    /**
     * 下载文档
     */
    public function downloadDocument(Document $document, User $user): StreamedResponse
    {
        if (!$this->validateDocumentAccess($document, $user)) {
            throw new \Exception('您没有权限访问此文档');
        }

        if (!Storage::disk('local')->exists($document->file_path)) {
            throw new \Exception('文档不存在或已被删除');
        }

        return Storage::disk('local')->download(
            $document->file_path,
            $document->display_file_name
        );
    }

    /**
     * 记录文档下载日志
     */
    public function logDownload(Document $document, User $user, ?string $ipAddress = null): DownloadLog
    {
        return DownloadLog::create([
            'document_id' => $document->id,
            'user_id' => $user->id,
            'downloaded_at' => now(),
            'ip_address' => $ipAddress ?? request()->ip(),
        ]);
    }
}
