<?php

namespace App\Http\Controllers;

use App\Enums\UserKycStatus;
use App\Http\Requests\StoreKycSubmissionRequest;
use App\Models\UserKycProfile;
use App\Services\AdminEventNotifier;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Inertia\Inertia;
use Inertia\Response;

class KycVerificationController extends Controller
{
    public function show(): Response
    {
        $user = request()->user();
        abort_unless($user !== null, 403);

        $profile = $user->kycProfile;

        return Inertia::render('kyc/verification', [
            'status' => $user->kyc_status->value,
            'rejection_reason' => $user->kyc_rejection_reason,
            'submission' => $profile === null
                ? null
                : [
                    'legal_first_name' => $profile->legal_first_name,
                    'legal_last_name' => $profile->legal_last_name,
                    'date_of_birth' => $profile->date_of_birth?->format('Y-m-d'),
                    'document_type' => $profile->document_type,
                    'document_number' => $profile->document_number,
                    'document_issuing_country' => Str::upper($profile->document_issuing_country),
                    'country_of_residence' => Str::upper($profile->country_of_residence),
                    'address_line1' => $profile->address_line1,
                    'address_line2' => $profile->address_line2,
                    'city' => $profile->city,
                    'region_state' => $profile->region_state,
                    'postal_code' => $profile->postal_code,
                    'occupation' => $profile->occupation,
                    'documents' => [
                        'front_uploaded' => (bool) $profile->document_front_path,
                        'back_uploaded' => (bool) $profile->document_back_path,
                        'selfie_uploaded' => (bool) $profile->selfie_document_path,
                    ],
                    'updated_at' => $profile->updated_at?->toIso8601String(),
                ],
        ]);
    }

    public function store(StoreKycSubmissionRequest $request): RedirectResponse
    {
        $user = $request->user();

        abort_unless($user !== null, 403);

        if ($user->kyc_status === UserKycStatus::PendingReview) {
            Inertia::flash('toast', [
                'type' => 'error',
                'message' => 'Tu verificación ya fue enviada y está pendiente de revisión.',
            ]);

            return to_route('kyc.show');
        }

        if (
            ! in_array($user->kyc_status, [UserKycStatus::RequiresSubmission, UserKycStatus::Rejected], true)
        ) {
            Inertia::flash('toast', [
                'type' => 'error',
                'message' => 'No puedes enviar una nueva solicitud KYC en tu estado actual.',
            ]);

            return to_route('kyc.show');
        }

        DB::transaction(function () use ($request, $user): void {
            $validated = Arr::except(
                $request->validated(),
                ['document_front', 'document_back', 'selfie_document'],
            );

            $validated['document_issuing_country'] = Str::upper($validated['document_issuing_country']);
            $validated['country_of_residence'] = Str::upper($validated['country_of_residence']);

            $dir = sprintf('users/%d/%s', $user->id, Str::uuid()->toString());

            $frontPath = $request->file('document_front')->store($dir, 'kyc');

            $backPath = null;
            if ($request->hasFile('document_back')) {
                $backPath = $request->file('document_back')->store($dir, 'kyc');
            }

            $selfiePath = null;
            if ($request->hasFile('selfie_document')) {
                $selfiePath = $request->file('selfie_document')->store($dir, 'kyc');
            }

            $existing = $user->kycProfile;
            if ($existing !== null) {
                $existing->deleteStoredDocuments();
            }

            UserKycProfile::query()->updateOrCreate(
                ['user_id' => $user->id],
                [
                    ...$validated,
                    'document_front_path' => $frontPath,
                    'document_back_path' => $backPath,
                    'selfie_document_path' => $selfiePath,
                    'reviewed_at' => null,
                    'reviewed_by' => null,
                ],
            );

            $user->forceFill([
                'kyc_status' => UserKycStatus::PendingReview,
                'kyc_rejection_reason' => null,
            ])->save();
        });

        $user->refresh();
        app(AdminEventNotifier::class)->notifyKycSubmitted($user);

        Inertia::flash('toast', [
            'type' => 'success',
            'message' => 'Información enviada. Tu cuenta quedará en revisión hasta que el equipo de cumplimiento la apruebe.',
        ]);

        return to_route('kyc.show');
    }
}
