<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\KycDocument;
use App\Services\InAppNotificationService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\ValidationException;

class KycController extends Controller
{
    public function store(Request $request): JsonResponse
    {
        $user = $request->user();

        abort_unless($user->role === 'liner', 403);

        $data = $request->validate([
            'document_type' => ['required', 'in:cni,passeport,titre_sejour'],
            'document_number' => ['required', 'string', 'max:120'],
            'document_url' => ['nullable', 'url'],
            'document_file' => ['nullable', 'file', 'mimes:jpg,jpeg,png,webp,pdf', 'max:10240'],
            'notes' => ['nullable', 'string', 'max:1000'],
        ]);

        $documentUrl = $data['document_url'] ?? null;
        if (!$request->hasFile('document_file') && !$documentUrl) {
            throw ValidationException::withMessages([
                'document_file' => 'Ajoutez un document KYC ou une URL valide.',
            ]);
        }

        if ($request->hasFile('document_file')) {
            $file = $request->file('document_file');
            $storedPath = $file->store('kyc-documents/' . $user->id, 'public');
            $documentUrl = Storage::disk('public')->url($storedPath);
        }

        $document = KycDocument::create([
            'user_id' => $user->id,
            'document_type' => $data['document_type'],
            'document_number' => $data['document_number'],
            'document_url' => $documentUrl,
            'notes' => $data['notes'] ?? null,
            'status' => 'pending',
        ]);

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

        return response()->json(['data' => $document], 201);
    }

    public function index(Request $request): JsonResponse
    {
        abort_unless($request->user()?->role === 'admin', 403);

        $query = KycDocument::query()->with('user:id,name,email');

        if ($request->filled('status')) {
            $query->where('status', $request->string('status'));
        }

        return response()->json([
            'data' => $query->latest()->paginate(20),
        ]);
    }

    public function review(
        Request $request,
        KycDocument $kycDocument,
        InAppNotificationService $notificationService,
    ): JsonResponse
    {
        $admin = $request->user();
        abort_unless($admin?->role === 'admin', 403);

        $data = $request->validate([
            'status' => ['required', 'in:approved,rejected'],
            'notes' => ['nullable', 'string', 'max:1000'],
        ]);

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

        $kycDocument->user()->update([
            'is_kyc_verified' => $data['status'] === 'approved',
        ]);

        $notificationService->notifyUser(
            $kycDocument->user_id,
            'kyc.reviewed',
            $data['status'] === 'approved' ? 'KYC valide' : 'KYC rejete',
            $data['status'] === 'approved'
                ? 'Votre dossier KYC est approuve.'
                : 'Votre dossier KYC a ete rejete. Consultez les notes.',
            [
                'kyc_document_id' => $kycDocument->id,
                'status' => $data['status'],
                'notes' => $data['notes'] ?? null,
            ],
        );

        return response()->json([
            'data' => $kycDocument->fresh(),
        ]);
    }
}
