<?php

declare(strict_types=1);

namespace Maestro\Core\Modules\Customers\Providers;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\ServiceProvider;
use Maestro\Core\DataTables\DataTableRegistry;
use Maestro\Core\Modules\Customers\DataTables\CustomersDataTable;
use Maestro\Core\Modules\Customers\Models\Customer;
use Maestro\Core\Support\CorePaths;
use Maestro\Core\Support\ModuleRuntimeState;

class CustomersModuleServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        Route::bind('customer', function (string $value): Customer {
            $user = Auth::user();
            abort_if(! $user, 404);

            return Customer::query()
                ->whereKey($value)
                ->firstOrFail();
        });

        if (ModuleRuntimeState::shouldLoadMigrations('customers')) {
            $this->loadMigrationsFrom(dirname(__DIR__).'/database/migrations');
        }

        $this->loadRoutesFrom(CorePaths::packageRoot().'/routes/modules/customers.php');

        if ($this->app->bound(DataTableRegistry::class)) {
            $this->app->make(DataTableRegistry::class)->register(CustomersDataTable::class, 'customers');
        }
    }
}
