<?php

namespace App\Services;

use App\Enums\AdminNotificationType;
use App\Mail\AdminInvestmentPendingMail;
use App\Mail\AdminKycSubmittedMail;
use App\Mail\AdminNewUserRegisteredMail;
use App\Mail\AdminWithdrawalRequestedMail;
use App\Models\AdminNotificationSetting;
use App\Models\Investment;
use App\Models\User;
use App\Models\WithdrawalRequest;
use Illuminate\Mail\Mailable;
use Illuminate\Support\Facades\Mail;

class AdminEventNotifier
{
    public function notifyNewUser(User $user): void
    {
        if ($user->is_admin) {
            return;
        }

        $this->dispatch(AdminNotificationType::NewUserRegistered, new AdminNewUserRegisteredMail($user));
    }

    public function notifyInvestmentPending(Investment $investment): void
    {
        $investment->loadMissing('user');

        $this->dispatch(AdminNotificationType::InvestmentPending, new AdminInvestmentPendingMail($investment));
    }

    public function notifyWithdrawalRequested(WithdrawalRequest $request): void
    {
        $request->loadMissing('requester');

        $this->dispatch(AdminNotificationType::WithdrawalRequested, new AdminWithdrawalRequestedMail($request));
    }

    public function notifyKycSubmitted(User $user): void
    {
        $user->loadMissing('kycProfile');

        $this->dispatch(AdminNotificationType::KycSubmitted, new AdminKycSubmittedMail($user));
    }

    private function dispatch(AdminNotificationType $type, Mailable $mail): void
    {
        if (! AdminNotificationSetting::current()->isEnabled($type)) {
            return;
        }

        User::query()
            ->where('is_admin', true)
            ->orderBy('id')
            ->each(function (User $admin) use ($mail): void {
                Mail::to($admin->email)->send(clone $mail);
            });
    }
}
