<?php

namespace App\Providers;

use App\Core\Contracts\RepositoryInterface;
use App\Core\Contracts\ServiceInterface;
use App\Models\User;
use App\Models\Wallet;
use App\Models\Transaction;
use App\Models\Payment;
use App\Models\BillService;
use App\Models\Beneficiary;
use App\Models\Setting;
use App\Models\UserNotification;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->bind(
            \App\Modules\Wallet\Interfaces\WalletRepositoryInterface::class,
            \App\Modules\Wallet\Repositories\WalletRepository::class
        );

        $this->app->bind(
            \App\Modules\Wallet\Interfaces\WalletServiceInterface::class,
            \App\Modules\Wallet\Services\WalletService::class
        );

        $this->app->bind(
            \App\Modules\Transactions\Interfaces\TransactionRepositoryInterface::class,
            \App\Modules\Transactions\Repositories\TransactionRepository::class
        );

        $this->app->bind(
            \App\Modules\Transactions\Interfaces\TransactionServiceInterface::class,
            \App\Modules\Transactions\Services\TransactionService::class
        );

        $this->app->bind(
            \App\Modules\Bills\Interfaces\BillServiceRepositoryInterface::class,
            \App\Modules\Bills\Repositories\BillServiceRepository::class
        );

        $this->app->bind(
            \App\Modules\ProviderIntegration\Interfaces\ProviderInterface::class,
            \App\Modules\ProviderIntegration\Services\VTPassProvider::class
        );
    }

    public function boot(): void
    {
        $this->configureRateLimiting();

        View::composer('*', function ($view) {
            if (auth()->check()) {
                $walletService = app(\App\Modules\Wallet\Interfaces\WalletServiceInterface::class);
                $wallet = $walletService->getOrCreateWallet(auth()->id());
                $view->with('walletBalance', $wallet->balance);
            }
        });
    }

    private function configureRateLimiting(): void
    {
        RateLimiter::for('api', function (Request $request) {
            return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
        });

        RateLimiter::for('purchase', function (Request $request) {
            return Limit::perMinute(10)->by($request->user()?->id ?: $request->ip());
        });

        RateLimiter::for('auth', function (Request $request) {
            return Limit::perMinute(5)->by($request->input('email'));
        });
    }
}
