<?php

namespace App\Providers;

use App\Models\Estimate;
use App\Models\JobCard;
use App\Models\User;
use App\Policies\EstimatePolicy;
use App\Policies\JobCardPolicy;
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 = [
        JobCard::class => JobCardPolicy::class,
        Estimate::class => EstimatePolicy::class,
    ];

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

        // Define gates for common permission checks
        Gate::define('access-admin-panel', function (User $user) {
            return $user->hasAnyRole(['admin', 'manager'], $user->branch_code);
        });

        Gate::define('manage-users', function (User $user) {
            return $user->hasPermission('users.create', $user->branch_code) ||
                   $user->hasPermission('users.update', $user->branch_code) ||
                   $user->hasPermission('users.delete', $user->branch_code);
        });

        Gate::define('view-reports', function (User $user) {
            return $user->hasAnyPermission([
                'reports.view',
                'reports.financial',
                'reports.operational',
            ], $user->branch_code);
        });

        Gate::define('manage-inventory', function (User $user) {
            return $user->hasAnyPermission([
                'inventory.create',
                'inventory.update',
                'inventory.delete',
                'inventory.stock-movements',
                'inventory.purchase-orders',
            ], $user->branch_code);
        });

        Gate::define('supervise-service', function (User $user) {
            return $user->hasAnyRole([
                'service_supervisor',
                'service_coordinator',
                'manager',
            ], $user->branch_code);
        });

        // Super admin gate (bypass all restrictions)
        Gate::before(function (User $user, string $ability) {
            if ($user->hasRole('admin')) {
                return true;
            }
        });
    }
}
