<?php

namespace App\Http\Controllers\Admin;

use App\Enums\UserKycStatus;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class AdminKycReviewController extends Controller
{
    public function index(Request $request): Response
    {
        abort_if($request->user() === null || ! $request->user()->is_admin, 403);

        $pending = User::query()
            ->where('is_admin', false)
            ->where('kyc_status', UserKycStatus::PendingReview)
            ->with('kycProfile')
            ->orderBy('updated_at')
            ->get()
            ->map(function (User $row): array {
                return [
                    'user_id' => $row->id,
                    'name' => trim($row->first_name.' '.$row->last_name),
                    'email' => $row->email,
                    'submitted_at' => $row->kycProfile?->updated_at?->toIso8601String(),
                ];
            });

        return Inertia::render('admin/kyc-review', [
            'pending' => $pending,
        ]);
    }

    public function showSubmission(Request $request, User $user): Response
    {
        abort_if($request->user() === null || ! $request->user()->is_admin, 403);
        abort_unless(! $user->is_admin, 404);

        abort_unless(
            $user->kyc_status === UserKycStatus::PendingReview,
            404,
        );

        abort_if($user->kycProfile === null, 404);

        $p = $user->kycProfile;

        return Inertia::render('admin/kyc-detail', [
            'user' => [
                'id' => $user->id,
                'name' => trim($user->first_name.' '.$user->last_name),
                'email' => $user->email,
            ],
            'profile' => [
                'legal_first_name' => $p->legal_first_name,
                'legal_last_name' => $p->legal_last_name,
                'date_of_birth' => $p->date_of_birth?->format('Y-m-d'),
                'document_type' => $p->document_type,
                'document_number' => $p->document_number,
                'document_issuing_country' => $p->document_issuing_country,
                'country_of_residence' => $p->country_of_residence,
                'address_line1' => $p->address_line1,
                'address_line2' => $p->address_line2,
                'city' => $p->city,
                'region_state' => $p->region_state,
                'postal_code' => $p->postal_code,
                'occupation' => $p->occupation,
                'document_front_path' => $p->document_front_path,
                'document_back_path' => $p->document_back_path,
                'selfie_document_path' => $p->selfie_document_path,
                'submitted_at' => $p->updated_at?->toIso8601String(),
            ],
        ]);
    }

    public function approve(Request $request, User $user): RedirectResponse
    {
        abort_if($request->user() === null || ! $request->user()->is_admin, 403);
        abort_unless(! $user->is_admin, 422);

        abort_unless(
            $user->kyc_status === UserKycStatus::PendingReview,
            422,
        );

        $user->kycProfile?->forceFill([
            'reviewed_at' => now(),
            'reviewed_by' => $request->user()->id,
        ])->save();

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

        Inertia::flash('toast', [
            'type' => 'success',
            'message' => 'La verificación KYC del usuario fue aprobada.',
        ]);

        return to_route('admin.kyc.index');
    }

    public function reject(Request $request, User $user): RedirectResponse
    {
        abort_if($request->user() === null || ! $request->user()->is_admin, 403);

        abort_unless(! $user->is_admin, 422);

        abort_unless(
            $user->kyc_status === UserKycStatus::PendingReview,
            422,
        );

        $validated = $request->validate([
            'reason' => ['required', 'string', 'max:2000'],
        ]);

        $user->kycProfile?->forceFill([
            'reviewed_at' => now(),
            'reviewed_by' => $request->user()->id,
        ])->save();

        $user->forceFill([
            'kyc_status' => UserKycStatus::Rejected,
            'kyc_rejection_reason' => $validated['reason'],
        ])->save();

        Inertia::flash('toast', [
            'type' => 'success',
            'message' => 'La verificación KYC fue rechazada y el inversionista puede corregir y reenviar.',
        ]);

        return to_route('admin.kyc.index');
    }
}
