<?php

namespace App\Services;

use App\Models\Permission;
use App\Models\User;

class PermissionService
{
    /**
     * Check if a user has a specific permission (e.g. 'customers.view').
     * Priority:
     * Explicit User Deny -> FALSE
     * Explicit User Allow -> TRUE
     * Role Permission -> TRUE
     * Default Deny -> FALSE
     */
    public function hasPermission(User $user, string $permissionSlug): bool
    {
        // Platform Super Admin bypass
        if ($user->isPlatformSuperAdmin()) {
            return true;
        }

        // 1. Check Explicit User Overrides
        $permission = Permission::where('slug', $permissionSlug)->first();
        if ($permission) {
            $override = $user->permissionOverrides()->where('permission_id', $permission->id)->first();
            if ($override !== null) {
                return (bool) $override->is_allowed;
            }
        }

        // 2. Check Roles Permissions
        foreach ($user->roles as $role) {
            if ($role->status !== 'active') {
                continue;
            }

            if ($role->permissions()->where('slug', $permissionSlug)->exists()) {
                return true;
            }
        }

        return false;
    }

    /**
     * Get user's resolved data scope (e.g. 'own', 'branch', 'all_branches', 'tenant', 'platform').
     */
    public function getDataScope(User $user): string
    {
        if ($user->isPlatformUser()) {
            return 'platform';
        }

        if ($user->data_scope_override) {
            return $user->data_scope_override;
        }

        $highestScope = 'own';
        $scopeHierarchy = [
            'own' => 1,
            'assigned' => 2,
            'counter' => 3,
            'department' => 4,
            'own_branch' => 5,
            'selected_branches' => 6,
            'all_branches' => 7,
            'tenant' => 8,
            'platform' => 9,
        ];

        foreach ($user->roles as $role) {
            $roleScope = $role->data_scope ?? 'own_branch';
            if (($scopeHierarchy[$roleScope] ?? 0) > ($scopeHierarchy[$highestScope] ?? 0)) {
                $highestScope = $roleScope;
            }
        }

        return $highestScope;
    }
}
