<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\UserKyc;
use App\Services\FraudDetectionService;
use App\Services\IdentityLimitService;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class KycController extends Controller
{
    public function index(): View
    {
        $kyc = UserKyc::query()->where('user_id', auth()->id())->first();

        return view('user.kyc', compact('kyc'));
    }

    public function store(
        Request $request,
        IdentityLimitService $identityLimitService,
        FraudDetectionService $fraudDetectionService
    ): RedirectResponse {
        $existingKyc = UserKyc::query()->where('user_id', auth()->id())->first();
        $validated = $request->validate([
            'pan_number' => ['required', 'string', 'max:25'],
            'aadhaar_number' => ['required', 'string', 'max:20'],
            'bank_account_number' => ['required', 'string', 'max:50'],
            'ifsc_code' => ['required', 'string', 'max:20'],
            'bank_name' => ['required', 'string', 'max:191'],
            'account_holder_name' => ['required', 'string', 'max:191'],
            'pan_document' => ['nullable', 'file', 'mimes:jpg,jpeg,png,pdf', 'max:4096'],
            'aadhaar_document' => [($existingKyc?->aadhaar_document_path ? 'nullable' : 'required'), 'file', 'mimes:jpg,jpeg,png,pdf', 'max:4096'],
            'cancelled_cheque' => ['nullable', 'file', 'mimes:jpg,jpeg,png,pdf', 'max:4096'],
            'photo' => [($existingKyc?->photo_path ? 'nullable' : 'required'), 'file', 'mimes:jpg,jpeg,png', 'max:4096'],
        ]);

        $identityPayload = [];
        if (! $existingKyc || $existingKyc->pan_number !== strtoupper($validated['pan_number'])) {
            $identityPayload['pan_number'] = $validated['pan_number'];
        }
        if (! $existingKyc || $existingKyc->bank_account_number !== strtoupper($validated['bank_account_number'])) {
            $identityPayload['bank_account_number'] = $validated['bank_account_number'];
        }

        if ($identityPayload !== []) {
            $identityLimitService->assertCanCreate($identityPayload);
        }

        DB::transaction(function () use ($validated, $request): void {
            $kyc = UserKyc::query()->firstOrNew(['user_id' => auth()->id()]);
            $kyc->pan_number = strtoupper($validated['pan_number']);
            $kyc->aadhaar_number = strtoupper($validated['aadhaar_number']);
            $kyc->bank_account_number = strtoupper($validated['bank_account_number']);
            $kyc->ifsc_code = strtoupper($validated['ifsc_code']);
            $kyc->bank_name = $validated['bank_name'];
            $kyc->account_holder_name = $validated['account_holder_name'];
            $kyc->status = 'pending';
            $kyc->rejection_reason = null;

            if ($request->hasFile('pan_document')) {
                $kyc->pan_document_path = $request->file('pan_document')->store('kyc/pan', 'public');
            }
            if ($request->hasFile('aadhaar_document')) {
                $kyc->aadhaar_document_path = $request->file('aadhaar_document')->store('kyc/aadhaar', 'public');
            }
            if ($request->hasFile('cancelled_cheque')) {
                $kyc->cancelled_cheque_path = $request->file('cancelled_cheque')->store('kyc/cheque', 'public');
            }
            if ($request->hasFile('photo')) {
                $kyc->photo_path = $request->file('photo')->store('kyc/photo', 'public');
            }

            $kyc->save();
        });

        $user = auth()->user();
        if ($user) {
            $fraudDetectionService->logIfSuspicious($user, [
                'ip_address' => (string) $request->ip(),
                'device' => (string) $request->userAgent(),
            ]);
        }

        return back()->with('status', 'KYC submitted for review.');
    }
}
