<?php

namespace App\Providers;

use App\Auth\DockerSessionGuard;
use App\Models\Bank;
use App\Policies\BankPolicy;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        // Set remember me duration from platform configuration
        $rememberMeDays = timebank_config('auth.remember_me_days', 90);
        $rememberMeMinutes = $rememberMeDays * 24 * 60; // Convert days to minutes

        // Use custom guard in Docker that doesn't migrate sessions
        if (env('IS_DOCKER', false)) {
            Auth::extend('session', function ($app, $name, array $config) use ($rememberMeMinutes) {
                $provider = Auth::createUserProvider($config['provider']);
                $guard = new DockerSessionGuard($name, $provider, $app['session.store']);

                // Set the cookie jar on the guard
                $guard->setCookieJar($app['cookie']);

                // If a request is available, set it on the guard
                if (method_exists($guard, 'setRequest')) {
                    $guard->setRequest($app->refresh('request', $guard, 'setRequest'));
                }

                // Set remember me duration
                $guard->setRememberDuration($rememberMeMinutes);

                return $guard;
            });
        }

        // Set remember me duration for all standard guards
        foreach (['web', 'organization', 'bank', 'admin'] as $guardName) {
            $guard = Auth::guard($guardName);
            if (method_exists($guard, 'setRememberDuration')) {
                $guard->setRememberDuration($rememberMeMinutes);
            }
        }

        // Spatie Laravel-Permissions:
        // Implicitly grant "Super-Admin" role all permission checks using can()
        Gate::before(function ($user, $ability) {
            if ($user->hasRole('Super-Admin')) {
                return true;
            }
        });

        // Add these explicit gate definitions:
        // These gates check permissions directly via Spatie's permission system
        Gate::define('manage banks', function ($user) {
            try {
                // Always check on web guard since that's where permissions are stored
                if ($user instanceof \App\Models\User) {
                    return $user->hasPermissionTo('manage banks', 'web');
                }
                return false;
            } catch (\Spatie\Permission\Exceptions\PermissionDoesNotExist $e) {
                return false;
            } catch (\Exception $e) {
                return false;
            }
        });

        Gate::define('manage organizations', function ($user) {
            try {
                // Always check on web guard since that's where permissions are stored
                if ($user instanceof \App\Models\User) {
                    return $user->hasPermissionTo('manage organizations', 'web');
                }
                return false;
            } catch (\Spatie\Permission\Exceptions\PermissionDoesNotExist $e) {
                return false;
            } catch (\Exception $e) {
                return false;
            }
        });

        Gate::define('manage admins', function ($user) {
            try {
                // Always check on web guard since that's where permissions are stored
                if ($user instanceof \App\Models\User) {
                    return $user->hasPermissionTo('manage admins', 'web');
                }
                return false;
            } catch (\Spatie\Permission\Exceptions\PermissionDoesNotExist $e) {
                return false;
            } catch (\Exception $e) {
                return false;
            }
        });

    }
}
