<?php

namespace AtlasAiDev\Awfah\REST;

use AtlasAiDev\Awfah\Abilities\Content_Steward_Abilities;
use AtlasAiDev\Awfah\Abilities\Custom_Post_Types_Abilities;
use AtlasAiDev\Awfah\Abilities\Debug_Log_Abilities;
use AtlasAiDev\Awfah\Abilities\Media_Abilities;
use AtlasAiDev\Awfah\Abilities\Pages_Abilities;
use AtlasAiDev\Awfah\Abilities\Posts_Abilities;
use AtlasAiDev\Awfah\Abilities\Rest_Api_Abilities;
use AtlasAiDev\Awfah\Abilities\Settings_Abilities;
use AtlasAiDev\Awfah\Abilities\Site_Info_Abilities;
use AtlasAiDev\Awfah\Abilities\Store_Manager_Abilities;
use AtlasAiDev\Awfah\Abilities\Users_Abilities;
use AtlasAiDev\Awfah\Plugin;
use WP_REST_Controller;
use WP_REST_Response;

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class Abilities_Controller extends WP_REST_Controller {

    public function __construct() {
        $this->namespace = 'awfah/v1';
        $this->rest_base = 'abilities';
    }

    public function register_routes(): void {
        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base,
            [
                [
                    'methods'             => 'GET',
                    'callback'            => [ $this, 'get_items' ],
                    'permission_callback' => [ $this, 'permissions_check' ],
                    'args'                => [
                        'context' => [
                            'type'              => 'string',
                            'enum'              => [ 'view', 'admin' ],
                            'default'           => 'view',
                            'sanitize_callback' => 'sanitize_text_field',
                        ],
                    ],
                ],
            ]
        );
    }

    public function permissions_check(): bool {
        return current_user_can( 'edit_posts' );
    }

    /**
     * @param \WP_REST_Request $request
     * @return \WP_REST_Response|\WP_Error
     */
    public function get_items( $request ) {
        $settings = Plugin::get_settings();
        $modules  = isset( $settings['modules'] ) ? (array) $settings['modules'] : [];
        $context  = $request->get_param( 'context' );

        $ability_classes = [
            Content_Steward_Abilities::class,
            Posts_Abilities::class,
            Pages_Abilities::class,
            Media_Abilities::class,
            Users_Abilities::class,
            Custom_Post_Types_Abilities::class,
            Rest_Api_Abilities::class,
            Site_Info_Abilities::class,
            Settings_Abilities::class,
            Store_Manager_Abilities::class,
            Debug_Log_Abilities::class,
        ];

        /**
         * Allow Pro or third-party plugins to add their ability classes.
         *
         * @param array $ability_classes Array of class names with static get_abilities().
         */
        $ability_classes = apply_filters( 'awfah_ability_classes', $ability_classes );

        $woo_active = class_exists( 'WooCommerce' );

        // Build full list filtered by global module toggles.
        $abilities = [];
        foreach ( $ability_classes as $class ) {
            // Skip Store Manager entirely when WooCommerce is not active.
            if ( ! $woo_active && Store_Manager_Abilities::class === $class ) {
                continue;
            }

            foreach ( $class::get_abilities() as $ability ) {
                $module_key = isset( $ability['module'] ) ? (string) $ability['module'] : '';
                if ( '' !== $module_key && empty( $modules[ $module_key ] ) ) {
                    continue;
                }
                $abilities[] = $this->format_ability( $ability, $modules );
            }
        }

        // Include external abilities (WordPress core + third-party plugins).
        if ( ! empty( $modules['external_abilities'] ) ) {
            foreach ( Plugin::get_external_abilities() as $ext_ability ) {
                $abilities[] = $this->format_ability( $ext_ability, $modules );
            }
        }

        // Admin context: return all enabled-module abilities for the Access Control config UI.
        if ( 'admin' === $context && current_user_can( 'manage_options' ) ) {
            return new WP_REST_Response( [ 'abilities' => $abilities ] );
        }

        // Apply role-based filtering if role_abilities is configured.
        $role_config = $settings['role_abilities'] ?? [];
        if ( ! empty( $role_config ) ) {
            $allowed    = Plugin::get_current_user_allowed_abilities();
            $abilities  = array_values( array_filter( $abilities, static function ( $ability ) use ( $allowed ) {
                return in_array( $ability['id'], $allowed, true );
            } ) );
        }

        return new WP_REST_Response( [ 'abilities' => $abilities ] );
    }

    private function format_ability( array $ability, array $modules ): array {
        $module_key    = isset( $ability['module'] ) ? (string) $ability['module'] : '';
        $is_enabled    = ! empty( $modules[ $module_key ] );
        $is_registered = function_exists( 'wp_register_ability' );

        return array_merge(
            $ability,
            [
                'enabled'    => $is_enabled,
                'registered' => $is_registered,
                'status'     => $is_enabled ? __( 'Enabled', 'ai-workflow-automation-ai-agent-hub' ) : __( 'Disabled', 'ai-workflow-automation-ai-agent-hub' ),
            ]
        );
    }
}
