<?php

namespace App\Http\Controllers\Api\V1\Documents;

use App\Domain\Documents\Models\Document;
use App\Domain\Documents\Services\DocumentService;
use App\Http\Controllers\Controller;
use App\Http\Requests\Documents\ReviewDocumentRequest;
use App\Http\Resources\DocumentResource;
use App\Support\ApiResponse;
use Illuminate\Http\JsonResponse;

/**
 * Verification decisions (§17B.11). Verify, reject, ask for a replacement, or
 * waive — each mapped to its own permission.
 */
class DocumentReviewController extends Controller
{
    public function __construct(private readonly DocumentService $documents) {}

    public function __invoke(ReviewDocumentRequest $request, Document $document): JsonResponse
    {
        $decision = $request->decision();
        $reason = (string) $request->input('reason');
        $actor = $request->user();

        $this->authorize(match ($decision) {
            'verify' => 'verify',
            'waive' => 'waive',
            default => 'reject',
        }, $document);

        $document = match ($decision) {
            'verify' => $this->documents->verify($document, $actor, $request->input('notes')),
            'reject' => $this->documents->reject($document, $actor, $reason, requestReupload: false),
            'request_reupload' => $this->documents->reject($document, $actor, $reason, requestReupload: true),
            'waive' => $this->documents->waive($document, $document->owner, $actor, $reason),
        };

        return ApiResponse::success(
            new DocumentResource($document->fresh()->load('documentType')),
            'Document review recorded.',
        );
    }
}
