<?php

namespace AtlasAiDev\Awfah\Abilities;

use WP_Error;
use WP_REST_Request;

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

class Store_Manager_Abilities {

	/**
	 * WooCommerce REST route definitions.
	 */
	private static array $rest_routes = [
		'awfah-store/wc-products-search'         => [ 'route' => '/wc/v3/products',                    'method' => 'GET' ],
		'awfah-store/wc-get-product'             => [ 'route' => '/wc/v3/products/%d',                 'method' => 'GET' ],
		'awfah-store/wc-add-product'             => [ 'route' => '/wc/v3/products',                    'method' => 'POST' ],
		'awfah-store/wc-update-product'          => [ 'route' => '/wc/v3/products/%d',                 'method' => 'POST' ],
		'awfah-store/wc-delete-product'          => [ 'route' => '/wc/v3/products/%d',                 'method' => 'DELETE' ],
		'awfah-store/wc-list-product-categories' => [ 'route' => '/wc/v3/products/categories',         'method' => 'GET' ],
		'awfah-store/wc-add-product-category'    => [ 'route' => '/wc/v3/products/categories',         'method' => 'POST' ],
		'awfah-store/wc-update-product-category' => [ 'route' => '/wc/v3/products/categories/%d',      'method' => 'POST' ],
		'awfah-store/wc-delete-product-category' => [ 'route' => '/wc/v3/products/categories/%d',      'method' => 'DELETE' ],
		'awfah-store/wc-list-product-tags'       => [ 'route' => '/wc/v3/products/tags',               'method' => 'GET' ],
		'awfah-store/wc-add-product-tag'         => [ 'route' => '/wc/v3/products/tags',               'method' => 'POST' ],
		'awfah-store/wc-update-product-tag'      => [ 'route' => '/wc/v3/products/tags/%d',            'method' => 'POST' ],
		'awfah-store/wc-delete-product-tag'      => [ 'route' => '/wc/v3/products/tags/%d',            'method' => 'DELETE' ],
		'awfah-store/wc-list-product-brands'     => [ 'route' => '/wc/v3/products/brands',             'method' => 'GET' ],
		'awfah-store/wc-add-product-brand'       => [ 'route' => '/wc/v3/products/brands',             'method' => 'POST' ],
		'awfah-store/wc-update-product-brand'    => [ 'route' => '/wc/v3/products/brands/%d',          'method' => 'POST' ],
		'awfah-store/wc-delete-product-brand'    => [ 'route' => '/wc/v3/products/brands/%d',          'method' => 'DELETE' ],
		'awfah-store/wc-orders-search'           => [ 'route' => '/wc/v3/orders',                      'method' => 'GET' ],
		'awfah-store/wc-reports-coupons-totals'  => [ 'route' => '/wc/v3/reports/coupons/totals',      'method' => 'GET' ],
		'awfah-store/wc-reports-customers-totals' => [ 'route' => '/wc/v3/reports/customers/totals',   'method' => 'GET' ],
		'awfah-store/wc-reports-orders-totals'   => [ 'route' => '/wc/v3/reports/orders/totals',       'method' => 'GET' ],
		'awfah-store/wc-reports-products-totals' => [ 'route' => '/wc/v3/reports/products/totals',     'method' => 'GET' ],
		'awfah-store/wc-reports-reviews-totals'  => [ 'route' => '/wc/v3/reports/reviews/totals',      'method' => 'GET' ],
		'awfah-store/wc-reports-sales'           => [ 'route' => '/wc/v3/reports/sales',               'method' => 'GET' ],
	];

	public static function get_abilities(): array {
		$meta = [ 'show_in_rest' => true, 'mcp' => [ 'public' => true ] ];
		$list_schema = [
			'type'       => 'object',
			'properties' => [
				'search'   => [ 'type' => 'string' ],
				'page'     => [ 'type' => 'integer', 'default' => 1 ],
				'per_page' => [ 'type' => 'integer', 'default' => 10 ],
			],
		];
		$id_schema = [
			'type'       => 'object',
			'required'   => [ 'id' ],
			'properties' => [ 'id' => [ 'type' => 'integer' ] ],
		];
		$term_add = [
			'type'       => 'object',
			'required'   => [ 'name' ],
			'properties' => [
				'name'        => [ 'type' => 'string' ],
				'slug'        => [ 'type' => 'string' ],
				'description' => [ 'type' => 'string' ],
				'parent'      => [ 'type' => 'integer' ],
			],
		];
		$term_update = [
			'type'       => 'object',
			'required'   => [ 'id' ],
			'properties' => [
				'id'          => [ 'type' => 'integer' ],
				'name'        => [ 'type' => 'string' ],
				'slug'        => [ 'type' => 'string' ],
				'description' => [ 'type' => 'string' ],
				'parent'      => [ 'type' => 'integer' ],
			],
		];

		return [
			// Products.
			[ 'id' => 'awfah-store/wc-products-search',         'module' => 'store_manager', 'label' => __( 'Search Products', 'ai-workflow-automation-ai-agent-hub' ),             'description' => __( 'Search and filter WooCommerce products with pagination.', 'ai-workflow-automation-ai-agent-hub' ),  'category' => 'awfah-store', 'input_schema' => $list_schema, 'meta' => [ 'show_in_rest' => true, 'mcp' => [ 'public' => true ], 'uri' => 'wordpress://ai-agent-hub/store/products', 'mimeType' => 'application/json' ] ],
			[ 'id' => 'awfah-store/wc-get-product',             'module' => 'store_manager', 'label' => __( 'Get Product', 'ai-workflow-automation-ai-agent-hub' ),                 'description' => __( 'Get a WooCommerce product by ID.', 'ai-workflow-automation-ai-agent-hub' ),                        'category' => 'awfah-store', 'input_schema' => $id_schema, 'meta' => [ 'show_in_rest' => true, 'mcp' => [ 'public' => true ], 'uri' => 'wordpress://ai-agent-hub/store/products/{id}', 'mimeType' => 'application/json' ] ],
			[ 'id' => 'awfah-store/wc-add-product',             'module' => 'store_manager', 'label' => __( 'Add Product', 'ai-workflow-automation-ai-agent-hub' ),                 'description' => __( 'Add a new WooCommerce product.', 'ai-workflow-automation-ai-agent-hub' ),                          'category' => 'awfah-store', 'input_schema' => [ 'type' => 'object', 'required' => [ 'name' ], 'properties' => [ 'name' => [ 'type' => 'string' ], 'type' => [ 'type' => 'string', 'default' => 'simple' ], 'regular_price' => [ 'type' => 'string' ], 'description' => [ 'type' => 'string' ], 'short_description' => [ 'type' => 'string' ], 'status' => [ 'type' => 'string', 'default' => 'draft' ] ] ], 'meta' => $meta ],
			[ 'id' => 'awfah-store/wc-update-product',          'module' => 'store_manager', 'label' => __( 'Update Product', 'ai-workflow-automation-ai-agent-hub' ),              'description' => __( 'Update a WooCommerce product by ID.', 'ai-workflow-automation-ai-agent-hub' ),                     'category' => 'awfah-store', 'input_schema' => [ 'type' => 'object', 'required' => [ 'id' ], 'properties' => [ 'id' => [ 'type' => 'integer' ], 'name' => [ 'type' => 'string' ], 'regular_price' => [ 'type' => 'string' ], 'description' => [ 'type' => 'string' ], 'status' => [ 'type' => 'string' ] ] ], 'meta' => $meta ],
			[ 'id' => 'awfah-store/wc-delete-product',          'module' => 'store_manager', 'label' => __( 'Delete Product', 'ai-workflow-automation-ai-agent-hub' ),              'description' => __( 'Delete a WooCommerce product by ID.', 'ai-workflow-automation-ai-agent-hub' ),                     'category' => 'awfah-store', 'input_schema' => [ 'type' => 'object', 'required' => [ 'id' ], 'properties' => [ 'id' => [ 'type' => 'integer' ], 'force' => [ 'type' => 'boolean', 'default' => false ] ] ], 'meta' => $meta ],
			// Product Categories.
			[ 'id' => 'awfah-store/wc-list-product-categories', 'module' => 'store_manager', 'label' => __( 'List Product Categories', 'ai-workflow-automation-ai-agent-hub' ),     'description' => __( 'List all WooCommerce product categories.', 'ai-workflow-automation-ai-agent-hub' ),                'category' => 'awfah-store', 'input_schema' => $list_schema, 'meta' => [ 'show_in_rest' => true, 'mcp' => [ 'public' => true ], 'uri' => 'wordpress://ai-agent-hub/store/categories', 'mimeType' => 'application/json' ] ],
			[ 'id' => 'awfah-store/wc-add-product-category',    'module' => 'store_manager', 'label' => __( 'Add Product Category', 'ai-workflow-automation-ai-agent-hub' ),        'description' => __( 'Add a new WooCommerce product category.', 'ai-workflow-automation-ai-agent-hub' ),                 'category' => 'awfah-store', 'input_schema' => $term_add, 'meta' => $meta ],
			[ 'id' => 'awfah-store/wc-update-product-category', 'module' => 'store_manager', 'label' => __( 'Update Product Category', 'ai-workflow-automation-ai-agent-hub' ),     'description' => __( 'Update a WooCommerce product category.', 'ai-workflow-automation-ai-agent-hub' ),                  'category' => 'awfah-store', 'input_schema' => $term_update, 'meta' => $meta ],
			[ 'id' => 'awfah-store/wc-delete-product-category', 'module' => 'store_manager', 'label' => __( 'Delete Product Category', 'ai-workflow-automation-ai-agent-hub' ),     'description' => __( 'Delete a WooCommerce product category.', 'ai-workflow-automation-ai-agent-hub' ),                  'category' => 'awfah-store', 'input_schema' => [ 'type' => 'object', 'required' => [ 'id' ], 'properties' => [ 'id' => [ 'type' => 'integer' ], 'force' => [ 'type' => 'boolean', 'default' => true ] ] ], 'meta' => $meta ],
			// Product Tags.
			[ 'id' => 'awfah-store/wc-list-product-tags',       'module' => 'store_manager', 'label' => __( 'List Product Tags', 'ai-workflow-automation-ai-agent-hub' ),           'description' => __( 'List all WooCommerce product tags.', 'ai-workflow-automation-ai-agent-hub' ),                      'category' => 'awfah-store', 'input_schema' => $list_schema, 'meta' => [ 'show_in_rest' => true, 'mcp' => [ 'public' => true ], 'uri' => 'wordpress://ai-agent-hub/store/tags', 'mimeType' => 'application/json' ] ],
			[ 'id' => 'awfah-store/wc-add-product-tag',         'module' => 'store_manager', 'label' => __( 'Add Product Tag', 'ai-workflow-automation-ai-agent-hub' ),             'description' => __( 'Add a new WooCommerce product tag.', 'ai-workflow-automation-ai-agent-hub' ),                      'category' => 'awfah-store', 'input_schema' => $term_add, 'meta' => $meta ],
			[ 'id' => 'awfah-store/wc-update-product-tag',      'module' => 'store_manager', 'label' => __( 'Update Product Tag', 'ai-workflow-automation-ai-agent-hub' ),          'description' => __( 'Update a WooCommerce product tag.', 'ai-workflow-automation-ai-agent-hub' ),                       'category' => 'awfah-store', 'input_schema' => $term_update, 'meta' => $meta ],
			[ 'id' => 'awfah-store/wc-delete-product-tag',      'module' => 'store_manager', 'label' => __( 'Delete Product Tag', 'ai-workflow-automation-ai-agent-hub' ),          'description' => __( 'Delete a WooCommerce product tag.', 'ai-workflow-automation-ai-agent-hub' ),                       'category' => 'awfah-store', 'input_schema' => [ 'type' => 'object', 'required' => [ 'id' ], 'properties' => [ 'id' => [ 'type' => 'integer' ], 'force' => [ 'type' => 'boolean', 'default' => true ] ] ], 'meta' => $meta ],
			// Product Brands.
			[ 'id' => 'awfah-store/wc-list-product-brands',     'module' => 'store_manager', 'label' => __( 'List Product Brands', 'ai-workflow-automation-ai-agent-hub' ),         'description' => __( 'List all WooCommerce product brands.', 'ai-workflow-automation-ai-agent-hub' ),                    'category' => 'awfah-store', 'input_schema' => $list_schema, 'meta' => [ 'show_in_rest' => true, 'mcp' => [ 'public' => true ], 'uri' => 'wordpress://ai-agent-hub/store/brands', 'mimeType' => 'application/json' ] ],
			[ 'id' => 'awfah-store/wc-add-product-brand',       'module' => 'store_manager', 'label' => __( 'Add Product Brand', 'ai-workflow-automation-ai-agent-hub' ),           'description' => __( 'Add a new WooCommerce product brand.', 'ai-workflow-automation-ai-agent-hub' ),                    'category' => 'awfah-store', 'input_schema' => $term_add, 'meta' => $meta ],
			[ 'id' => 'awfah-store/wc-update-product-brand',    'module' => 'store_manager', 'label' => __( 'Update Product Brand', 'ai-workflow-automation-ai-agent-hub' ),        'description' => __( 'Update a WooCommerce product brand.', 'ai-workflow-automation-ai-agent-hub' ),                     'category' => 'awfah-store', 'input_schema' => $term_update, 'meta' => $meta ],
			[ 'id' => 'awfah-store/wc-delete-product-brand',    'module' => 'store_manager', 'label' => __( 'Delete Product Brand', 'ai-workflow-automation-ai-agent-hub' ),        'description' => __( 'Delete a WooCommerce product brand.', 'ai-workflow-automation-ai-agent-hub' ),                     'category' => 'awfah-store', 'input_schema' => [ 'type' => 'object', 'required' => [ 'id' ], 'properties' => [ 'id' => [ 'type' => 'integer' ], 'force' => [ 'type' => 'boolean', 'default' => true ] ] ], 'meta' => $meta ],
			// Orders.
			[ 'id' => 'awfah-store/wc-orders-search',           'module' => 'store_manager', 'label' => __( 'Search Orders', 'ai-workflow-automation-ai-agent-hub' ),               'description' => __( 'Get a list of WooCommerce orders.', 'ai-workflow-automation-ai-agent-hub' ),                      'category' => 'awfah-store', 'input_schema' => $list_schema, 'meta' => [ 'show_in_rest' => true, 'mcp' => [ 'public' => true ], 'uri' => 'wordpress://ai-agent-hub/store/orders', 'mimeType' => 'application/json' ] ],
			// Reports.
			[ 'id' => 'awfah-store/wc-reports-coupons-totals',  'module' => 'store_manager', 'label' => __( 'Get Coupons Report', 'ai-workflow-automation-ai-agent-hub' ),          'description' => __( 'Get WooCommerce coupons totals report.', 'ai-workflow-automation-ai-agent-hub' ),                  'category' => 'awfah-store', 'input_schema' => [ 'type' => 'object', 'properties' => (object) [] ], 'meta' => [ 'show_in_rest' => true, 'mcp' => [ 'public' => true ], 'uri' => 'wordpress://ai-agent-hub/store/reports/coupons', 'mimeType' => 'application/json' ] ],
			[ 'id' => 'awfah-store/wc-reports-customers-totals', 'module' => 'store_manager', 'label' => __( 'Get Customers Report', 'ai-workflow-automation-ai-agent-hub' ),       'description' => __( 'Get WooCommerce customers totals report.', 'ai-workflow-automation-ai-agent-hub' ),                'category' => 'awfah-store', 'input_schema' => [ 'type' => 'object', 'properties' => (object) [] ], 'meta' => [ 'show_in_rest' => true, 'mcp' => [ 'public' => true ], 'uri' => 'wordpress://ai-agent-hub/store/reports/customers', 'mimeType' => 'application/json' ] ],
			[ 'id' => 'awfah-store/wc-reports-orders-totals',   'module' => 'store_manager', 'label' => __( 'Get Orders Report', 'ai-workflow-automation-ai-agent-hub' ),           'description' => __( 'Get WooCommerce orders totals report.', 'ai-workflow-automation-ai-agent-hub' ),                   'category' => 'awfah-store', 'input_schema' => [ 'type' => 'object', 'properties' => (object) [] ], 'meta' => [ 'show_in_rest' => true, 'mcp' => [ 'public' => true ], 'uri' => 'wordpress://ai-agent-hub/store/reports/orders', 'mimeType' => 'application/json' ] ],
			[ 'id' => 'awfah-store/wc-reports-products-totals', 'module' => 'store_manager', 'label' => __( 'Get Products Report', 'ai-workflow-automation-ai-agent-hub' ),         'description' => __( 'Get WooCommerce products totals report.', 'ai-workflow-automation-ai-agent-hub' ),                 'category' => 'awfah-store', 'input_schema' => [ 'type' => 'object', 'properties' => (object) [] ], 'meta' => [ 'show_in_rest' => true, 'mcp' => [ 'public' => true ], 'uri' => 'wordpress://ai-agent-hub/store/reports/products', 'mimeType' => 'application/json' ] ],
			[ 'id' => 'awfah-store/wc-reports-reviews-totals',  'module' => 'store_manager', 'label' => __( 'Get Reviews Report', 'ai-workflow-automation-ai-agent-hub' ),          'description' => __( 'Get WooCommerce reviews totals report.', 'ai-workflow-automation-ai-agent-hub' ),                  'category' => 'awfah-store', 'input_schema' => [ 'type' => 'object', 'properties' => (object) [] ], 'meta' => [ 'show_in_rest' => true, 'mcp' => [ 'public' => true ], 'uri' => 'wordpress://ai-agent-hub/store/reports/reviews', 'mimeType' => 'application/json' ] ],
			[ 'id' => 'awfah-store/wc-reports-sales',           'module' => 'store_manager', 'label' => __( 'Get Sales Report', 'ai-workflow-automation-ai-agent-hub' ),            'description' => __( 'Get WooCommerce sales report.', 'ai-workflow-automation-ai-agent-hub' ),                           'category' => 'awfah-store', 'input_schema' => [ 'type' => 'object', 'properties' => (object) [] ], 'meta' => [ 'show_in_rest' => true, 'mcp' => [ 'public' => true ], 'uri' => 'wordpress://ai-agent-hub/store/reports/sales', 'mimeType' => 'application/json' ] ],
		];
	}

	public static function register(): void {
		if ( ! function_exists( 'wp_register_ability' ) ) {
			return;
		}

		// Only register if WooCommerce is active.
		if ( ! class_exists( 'WooCommerce' ) ) {
			return;
		}

		foreach ( self::get_abilities() as $ability ) {
			$config = $ability;
			$id     = $ability['id'];
			unset( $config['id'], $config['module'] );

			// Workaround: MCP ResourcesHandler calls execute() with no input.
			// Adding default empty object prevents "input is not of type object" validation error.
			if ( isset( $config['meta']['uri'], $config['input_schema']['type'] ) && 'object' === $config['input_schema']['type'] ) {
				$config['input_schema']['default'] = (object) [];
			}

			wp_register_ability( $id, array_merge( $config, [
				'execute_callback'    => self::make_callback( $id ),
				'permission_callback' => static function () use ( $id ) {
					return \AtlasAiDev\Awfah\Plugin::check_ability_access( $id, [ 'manage_woocommerce', 'manage_options' ] );
				},
			] ) );
		}
	}

	/**
	 * Generic execute callback that dispatches to the correct WooCommerce REST route.
	 *
	 * @param array|null $input Input parameters.
	 * @return array|WP_Error
	 */
	public static function execute_generic( $input = null ) {
		$input = (array) $input;

		// Determine which ability is being executed from the call context.
		// The Abilities API passes the ability name; we look it up in rest_routes.
		$ability_name = $input['__ability_name'] ?? '';

		// If __ability_name isn't provided, try to find the route from backtrace.
		if ( empty( $ability_name ) || ! isset( self::$rest_routes[ $ability_name ] ) ) {
			// Fallback: iterate to match based on input signature - not ideal.
			// Instead, register individual callbacks per ability.
			return new WP_Error( 'unknown_ability', __( 'Could not determine ability.', 'ai-workflow-automation-ai-agent-hub' ) );
		}

		unset( $input['__ability_name'] );
		$route_config = self::$rest_routes[ $ability_name ];
		$route        = $route_config['route'];
		$method       = $route_config['method'];

		// Handle {id} in route.
		if ( strpos( $route, '%d' ) !== false && isset( $input['id'] ) ) {
			$route = sprintf( $route, (int) $input['id'] );
			unset( $input['id'] );
		}

		return self::dispatch_rest( $method, $route, $input );
	}

	/**
	 * Register all abilities with individual execute callbacks.
	 * This override replaces the generic approach with per-ability closures.
	 */
	private static function make_callback( string $ability_id ): \Closure {
		return static function ( $input = null ) use ( $ability_id ) {
			$input = (array) $input;

			if ( ! isset( self::$rest_routes[ $ability_id ] ) ) {
				return new WP_Error( 'unknown_ability', __( 'Unknown ability.', 'ai-workflow-automation-ai-agent-hub' ) );
			}

			$route_config = self::$rest_routes[ $ability_id ];
			$route        = $route_config['route'];
			$method       = $route_config['method'];

			if ( strpos( $route, '%d' ) !== false && isset( $input['id'] ) ) {
				$route = sprintf( $route, (int) $input['id'] );
				unset( $input['id'] );
			}

			return self::dispatch_rest( $method, $route, $input );
		};
	}

	private static function dispatch_rest( string $method, string $route, array $params = [] ) {
		$request = new WP_REST_Request( $method, $route );
		foreach ( $params as $key => $value ) {
			$request->set_param( $key, $value );
		}
		$response = rest_do_request( $request );
		if ( $response->is_error() ) {
			$error = $response->as_error();
			return new WP_Error( $error->get_error_code(), $error->get_error_message(), [ 'status' => $response->get_status() ] );
		}
		$data = $response->get_data();
		if ( is_array( $data ) && array_is_list( $data ) ) {
			return [ 'results' => $data ];
		}
		return $data;
	}
}
