<?php

namespace App\Providers;

use AbdulmajeedJamaan\FilamentTranslatableTabs\TranslatableTabs;
use BezhanSalleh\LanguageSwitch\Events\LocaleChanged;
use BezhanSalleh\LanguageSwitch\LanguageSwitch;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\ServiceProvider;
use Spatie\Translatable\HasTranslations;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        // ...
    }

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        Model::unguard();
        Model::shouldBeStrict(! app()->isProduction());

        TranslatableTabs::configureUsing(function (TranslatableTabs $component) {
            $component
                ->localesLabels(baseLocales())
                ->locales(array_keys(baseLocales()));
        });

        LanguageSwitch::configureUsing(function (LanguageSwitch $switch) {
            $switch
                ->locales(['tk', 'en', 'ru']);
        });

        Event::listen(function (LocaleChanged $event) {
            if (array_key_exists($event->locale, baseLocales())) {
                user()->update(['locale' => $event->locale]);
            }
        });

        /**
         * Order by translation for spatie/laravel-translatable
         *
         * @param  string  $field
         * @param  string  $order
         * @param  string  $locale
         * @return \Illuminate\Database\Eloquent\Builder
         */
        Builder::macro('orderByTranslation', function (string $field, string $order = 'asc', ?string $locale = null) {
            /** @var \Illuminate\Database\Eloquent\Builder */
            $builder = $this; // @phpstan-ignore-line

            if (
                in_array(HasTranslations::class, class_uses($builder->model)) // @phpstan-ignore-line
                && in_array($field, $builder->model->translatable)
                && config('database.default') === 'pgsql'
            ) {
                $locale = $locale ?? app()->getLocale();
                $builder->query->orderByRaw("$field->>'$locale' $order");
            } else {
                $builder->query->orderBy($field, $order);
            }

            return $builder;
        });
    }
}
