<?php

namespace App\Http\Controllers;

use App\Models\Loan;
use App\Models\LoanDocument;
use App\Services\DocxContractTemplateService;
use App\Services\SecureFileService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\View\View;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Throwable;

class LoanDocumentReviewController extends Controller
{
    public function __invoke(
        Request $request,
        Loan $loan,
        LoanDocument $document,
        SecureFileService $files,
        DocxContractTemplateService $docx,
    ): View|StreamedResponse {
        abort_unless($request->user()->canAccessBranch($loan->branch_id), 403);
        abort_unless($document->loan_id === $loan->id, 404);

        $extension = strtolower(pathinfo($document->original_name, PATHINFO_EXTENSION));
        $mime = strtolower((string) $document->mime_type);

        if ($extension === 'pdf' || $mime === 'application/pdf') {
            return $files->inline($document->file_path, $document->original_name, 'application/pdf');
        }

        if (in_array($extension, ['jpg', 'jpeg', 'png', 'webp'], true) || str_starts_with($mime, 'image/')) {
            return $files->inline($document->file_path, $document->original_name, $mime ?: null);
        }

        $blocks = [];
        $previewAvailable = false;
        $previewError = null;

        if ($extension === 'docx') {
            abort_unless(Storage::disk('local')->exists($document->file_path), 404);

            try {
                $inspection = $docx->inspectPath(Storage::disk('local')->path($document->file_path));
                $blocks = $inspection['blocks'] ?? [];
                $previewAvailable = true;
            } catch (Throwable $exception) {
                $previewError = 'This Word document could not be rendered for in-system review. Download the original file to inspect it.';
            }
        }

        return view('loans.document-review', [
            'loan' => $loan->loadMissing(['customer', 'branch']),
            'document' => $document->loadMissing('uploader'),
            'blocks' => $blocks,
            'previewAvailable' => $previewAvailable,
            'previewError' => $previewError,
        ]);
    }
}
