<?php

namespace App\Http\Controllers\Admin;

use App\Enums\VerificationStatus;
use App\Http\Controllers\Controller;
use App\Models\Document;
use App\Services\AuditLogger;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class DocumentReviewController extends Controller
{
    public function __construct(protected AuditLogger $audit) {}

    public function verify(Request $request, Document $document): RedirectResponse
    {
        $document->update([
            'verification_status' => VerificationStatus::Verified,
            'verified_by' => $request->user()->id,
            'verified_at' => now(),
            'rejection_reason' => null,
        ]);

        $this->audit->log(AuditLogger::DOCUMENT_VERIFIED, $document, [], [
            'document_type' => $document->document_type,
            'application_id' => $document->application_id,
        ]);

        return back()->with('status', 'Document verified.');
    }

    public function reject(Request $request, Document $document): RedirectResponse
    {
        $data = $request->validate([
            'reason' => ['required', 'string', 'min:5', 'max:1000'],
        ]);

        $document->update([
            'verification_status' => VerificationStatus::Rejected,
            'verified_by' => $request->user()->id,
            'verified_at' => now(),
            'rejection_reason' => $data['reason'],
        ]);

        $this->audit->log(AuditLogger::DOCUMENT_REJECTED, $document, [], [
            'document_type' => $document->document_type,
            'reason' => $data['reason'],
        ]);

        return back()->with('status', 'Document rejected. The applicant can upload a replacement.');
    }
}
