<?php

namespace App\Http\Controllers\Web\Bo;

use App\Http\Controllers\Controller;
use App\Models\KycDocument;
use App\Services\InAppNotificationService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class KycModerationController extends Controller
{
    public function approve(
        Request $request,
        KycDocument $kycDocument,
        InAppNotificationService $notificationService,
    ): RedirectResponse
    {
        $admin = $request->user();

        $kycDocument->update([
            'status' => 'approved',
            'validated_by' => $admin?->id,
            'validated_at' => now(),
            'notes' => $kycDocument->notes,
        ]);

        $kycDocument->user()->update(['is_kyc_verified' => true]);

        $notificationService->notifyUser(
            $kycDocument->user_id,
            'kyc.reviewed',
            'KYC valide',
            'Votre dossier KYC est approuve.',
            [
                'kyc_document_id' => $kycDocument->id,
                'status' => 'approved',
            ],
        );

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

    public function reject(
        Request $request,
        KycDocument $kycDocument,
        InAppNotificationService $notificationService,
    ): RedirectResponse
    {
        $admin = $request->user();
        $data = $request->validate([
            'reason' => ['nullable', 'string', 'max:500'],
        ]);

        $kycDocument->update([
            'status' => 'rejected',
            'validated_by' => $admin?->id,
            'validated_at' => now(),
            'notes' => $data['reason'] ?? $kycDocument->notes,
        ]);

        $kycDocument->user()->update(['is_kyc_verified' => false]);

        $notificationService->notifyUser(
            $kycDocument->user_id,
            'kyc.reviewed',
            'KYC rejete',
            'Votre dossier KYC a ete rejete. Consultez le motif dans le BO/API.',
            [
                'kyc_document_id' => $kycDocument->id,
                'status' => 'rejected',
                'reason' => $data['reason'] ?? null,
            ],
        );

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