<?php

namespace App\Providers;

// use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The model to policy mappings for the application.
     *
     * @var array<class-string, class-string>
     */
    protected $policies = [
        \App\Models\Ad::class => \App\Policies\AdPolicy::class,
        \App\Models\PerformanceForecast::class => \App\Policies\PerformanceForecastPolicy::class,
        \App\Models\LocalizedContent::class => \App\Policies\LocalizedContentPolicy::class,
        \App\Models\KnowledgeBaseDocument::class => \App\Policies\SupportPolicy::class,
        \App\Models\SupportConversation::class => \App\Policies\SupportPolicy::class,
    ];

    /**
     * Register any authentication / authorization services.
     */
    public function boot(): void
    {
        $this->registerPolicies();

        // Define a gate for creator role
        Gate::define('creator', function ($user) {
            return $user->hasRole('creator');
        });

        // Define a gate for brand_admin role
        Gate::define('brand_admin', function ($user) {
            return $user->hasRole('brand_admin');
        });

        // Define a gate for superadmin role
        Gate::define('superadmin', function ($user) {
            return $user->hasRole('superadmin');
        });

        // Define a gate for agency role
        Gate::define('agency', function ($user) {
            return $user->hasRole('agency');
        });

        // Define a gate for user role
        Gate::define('user', function ($user) {
            return $user->hasRole('user');
        });

        // Define gates for support management
        Gate::define('manage-support', function ($user, $brand) {
            return app(\App\Policies\SupportPolicy::class)->manageSupport($user, $brand);
        });

        Gate::define('manage-localization', function ($user, $brand) {
            // Reuse existing localization gate or create new one
            if ($user->brand_id === $brand->id) {
                return $user->hasRole(['brand_admin', 'brand_owner']);
            }
            if ($user->hasRole('agency')) {
                return $user->brands()->where('brands.id', $brand->id)->exists();
            }
            return $user->hasRole('super_admin');
        });
    }
}