<?php

namespace App\Providers;

use App\Domains\Translation\Providers\DatabaseTranslationLoader;
use App\Domains\Workspace\Models\Workspace;
use App\Domains\Workspace\Policies\WorkspacePolicy;
use App\Domains\Workspace\Services\CurrentWorkspace;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;
use Laravel\Cashier\Cashier;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        $this->app->singleton(CurrentWorkspace::class);

        // TranslationServiceProvider is deferred and re-binds translation.loader when it
        // resolves. We extend 'translator' to swap in our DB loader after the instance is
        // created, then freeze it in the container so app('translation.loader') is consistent.
        $this->app->extend('translator', function ($translator, $app) {
            $loader = new DatabaseTranslationLoader;
            $app->instance('translation.loader', $loader);
            $prop = new \ReflectionProperty($translator, 'loader');
            $prop->setValue($translator, $loader);

            return $translator;
        });
    }

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        Gate::policy(Workspace::class, WorkspacePolicy::class);

        Cashier::useCustomerModel(Workspace::class);
    }
}
