<?php

namespace App\Http\Controllers\Admin;

use App\Enums\InvestmentStatus;
use App\Enums\UserKycStatus;
use App\Enums\WithdrawalRequestStatus;
use App\Http\Controllers\Controller;
use App\Models\Investment;
use App\Models\User;
use App\Models\WithdrawalRequest;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;
use Inertia\Response;

class AdminDashboardController extends Controller
{
    public function index(): Response
    {
        $investorsRegistered = User::query()
            ->where('is_admin', false)
            ->count();

        $adminsRegistered = User::query()
            ->where('is_admin', true)
            ->count();

        $kycPendingReview = User::query()
            ->where('is_admin', false)
            ->where('kyc_status', UserKycStatus::PendingReview)
            ->count();

        $kycRequiresSubmission = User::query()
            ->where('is_admin', false)
            ->where('kyc_status', UserKycStatus::RequiresSubmission)
            ->count();

        $investmentsPendingConfirm = Investment::query()
            ->where('status', InvestmentStatus::Pending)
            ->count();

        $activeInvestments = Investment::query()
            ->where('status', InvestmentStatus::Active)
            ->count();

        $capitalUsdActiveTotal = round(
            (float) Investment::query()
                ->where('status', InvestmentStatus::Active)
                ->sum(DB::raw('COALESCE(capital_balance, amount)')),
            2,
        );

        $withdrawalsPendingApproval = WithdrawalRequest::query()
            ->where('status', WithdrawalRequestStatus::Pending)
            ->count();

        return Inertia::render('admin/dashboard', [
            'metrics' => [
                'investors_registered' => $investorsRegistered,
                'admins_registered' => $adminsRegistered,
                'kyc_pending_review' => $kycPendingReview,
                'kyc_requires_submission' => $kycRequiresSubmission,
                'investments_pending_confirm' => $investmentsPendingConfirm,
                'active_investments' => $activeInvestments,
                'capital_usd_active_total' => $capitalUsdActiveTotal,
                'withdrawals_pending_approval' => $withdrawalsPendingApproval,
            ],
        ]);
    }
}
