<?php

namespace App\Providers;

use App\Modules\Pilkades\Models\Banner;
use App\Modules\Pilkades\Models\Candidate;
use App\Modules\Pilkades\Models\Contact;
use App\Modules\Pilkades\Models\Countdown;
use App\Modules\Pilkades\Models\Desa;
use App\Modules\Pilkades\Models\Faq;
use App\Modules\Pilkades\Models\LandingPage;
use App\Modules\Pilkades\Models\Tps;
use App\Modules\Pilkades\Models\Voter;
use App\Modules\Pilkades\Observers\InvalidatesLandingPageCache;
use App\Modules\Pilkades\Policies\CandidatePolicy;
use App\Modules\Pilkades\Policies\DesaPolicy;
use App\Modules\Pilkades\Policies\VoterPolicy;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Str;

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

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        Gate::policy(Desa::class, DesaPolicy::class);
        Gate::policy(Candidate::class, CandidatePolicy::class);
        Gate::policy(Voter::class, VoterPolicy::class);

        foreach ([LandingPage::class, Banner::class, Countdown::class, Candidate::class, Faq::class, Contact::class, Tps::class] as $model) {
            $model::observe(InvalidatesLandingPageCache::class);
        }

        // Module models live under App\Modules\{Module}\Models, not App\Models,
        // so the default "strip App\Models\ prefix" factory resolver can't
        // find their factories. Map them to Database\Factories\Pilkades\*.
        Factory::guessFactoryNamesUsing(function (string $modelName) {
            if (Str::startsWith($modelName, 'App\\Modules\\Pilkades\\Models\\')) {
                $shortName = Str::after($modelName, 'App\\Modules\\Pilkades\\Models\\');

                return "Database\\Factories\\Pilkades\\{$shortName}Factory";
            }

            return 'Database\\Factories\\'.Str::after($modelName, 'App\\Models\\').'Factory';
        });
    }
}
