<?php

namespace Mtc\Plugins\WeightVerification\Providers;

use Illuminate\Support\Facades\Event;
use Illuminate\Support\ServiceProvider;
use Mtc\Plugins\WeightVerification\Src\WeightVerificationService;
use Mtc\Shop\Events\OrderPaidEvent;

class WeightVerificationServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->loadRoutesFrom(__DIR__ . '/../routes/web.php');
        $this->loadMigrationsFrom(__DIR__ . '/../database/migrations');
        $this->mergeConfigFrom(__DIR__ . '/../config/weight_verification.php', 'weight_verification');

        $this->app->singleton(WeightVerificationService::class);
    }

    public function boot(): void
    {
        if (!config('weight_verification.enabled')) {
            return;
        }

        $this->registerEvents();
    }

    /**
     * Create a pending verification when a flagged order is paid.
     */
    protected function registerEvents(): void
    {
        Event::listen(OrderPaidEvent::class, function (OrderPaidEvent $event) {
            $this->app->make(WeightVerificationService::class)
                ->handleOrderPaid($event->getOrder()->getId());
        });
    }
}
