<?php

namespace Licenzo\Framework\Auth;

use Licenzo\Framework\Contracts\Auth\Policy;
use Licenzo\Framework\Http\Request;

/**
 * Base Policy implementation
 */
abstract class BasePolicy implements Policy
{
    /**
     * Default error message for authorization failures.
     */
    protected string $defaultMessage = 'Access denied. You do not have permission to perform this action.';

    /**
     * Required WordPress capabilities.
     */
    protected array $requiredCapabilities = ['manage_options'];

    /**
     * Authorize the request.
     * 
     * This method should be overridden by concrete policy implementations.
     */
    public function authorize(Request $request, ...$arguments): bool
    {
        // Default implementation checks WordPress capabilities
        return $this->checkCapabilities();
    }

    /**
     * Get the authorization failure message.
     */
    public function message(): string
    {
        return $this->defaultMessage;
    }

    /**
     * Get the required WordPress capabilities.
     */
    public function getRequiredCapabilities(): array
    {
        return $this->requiredCapabilities;
    }

    /**
     * Check if current user has required capabilities.
     */
    protected function checkCapabilities(): bool
    {
        if (empty($this->requiredCapabilities)) {
            return true;
        }

        foreach ($this->requiredCapabilities as $capability) {
            if (!current_user_can($capability)) {
                return false;
            }
        }

        return true;
    }

    /**
     * Check if user is logged in.
     */
    protected function isLoggedIn(): bool
    {
        return is_user_logged_in();
    }

    /**
     * Get current user ID.
     */
    protected function getCurrentUserId(): int
    {
        return get_current_user_id();
    }

    /**
     * Check if current user has a specific role.
     */
    protected function hasRole(string $role): bool
    {
        $user = wp_get_current_user();
        return in_array($role, $user->roles ?? []);
    }

    /**
     * Check if current user can manage a specific resource.
     */
    protected function canManageResource(string $resourceType, $resourceId = null): bool
    {
        // Basic implementation - can be overridden
        return current_user_can('manage_options');
    }
}
