<?php

namespace App\Http\Controllers;

use App\Models\Document;
use App\Services\DocumentService;
use App\Services\MarkdownRenderService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Storage;

class DocumentController extends Controller
{
    protected DocumentService $documentService;
    protected MarkdownRenderService $markdownRenderService;

    public function __construct(
        DocumentService $documentService,
        MarkdownRenderService $markdownRenderService
    ) {
        $this->documentService = $documentService;
        $this->markdownRenderService = $markdownRenderService;
    }

    /**
     * 预览文档的 Markdown 内容（支持图片显示）
     * 需求：11.1, 11.3, 11.4
     * 
     * @param Document $document
     * @return \Illuminate\View\View|\Illuminate\Http\RedirectResponse
     */
    public function preview(Document $document)
    {
        // 验证用户权限（使用 DocumentPolicy）
        // 需求：11.3
        if (!Gate::allows('view', $document)) {
            abort(403, '您没有权限预览此文档');
        }

        // 检查文档是否已完成转换
        if ($document->conversion_status !== 'completed') {
            return view('documents.preview', [
                'document' => $document,
                'markdownHtml' => null,
            ]);
        }

        $markdownHtml = null;

        try {
            // 使用 DocumentPreviewService 的 Markdown 预览方法
            // 这会修复图片路径并渲染 Markdown
            // 需求：11.1
            $previewService = app(\App\Services\DocumentPreviewService::class);
            $markdownHtml = $previewService->convertMarkdownToHtml($document);
        } catch (\Exception $e) {
            // 记录错误但不中断流程
            \Log::error('Markdown 预览失败', [
                'document_id' => $document->id,
                'error' => $e->getMessage(),
            ]);
        }

        // 处理内容为空的情况
        // 需求：11.4
        // 返回渲染后的 HTML 视图
        return view('documents.preview', [
            'document' => $document,
            'markdownHtml' => $markdownHtml,
        ]);
    }

    /**
     * 下载文档
     * 
     * @param Document $document
     * @return \Symfony\Component\HttpFoundation\StreamedResponse
     */
    public function download(Document $document)
    {
        // 验证用户权限
        if (!Gate::allows('download', $document)) {
            abort(403, '您没有权限下载此文档');
        }

        $user = auth()->user();

        try {
            // 记录下载日志
            $this->documentService->logDownload($document, $user);
            
            // 返回文件下载响应
            return $this->documentService->downloadDocument($document, $user);
        } catch (\Exception $e) {
            abort(500, '下载失败：' . $e->getMessage());
        }
    }
}
