<?php

namespace BitApps\PiPro\src\Integrations\FluentCart;

use BitApps\Pi\Helpers\Utility;
use BitApps\Pi\src\Flow\NodeInfoProvider;
use BitApps\Pi\src\Interfaces\ActionInterface;

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


class FluentCartAction implements ActionInterface
{
    /**
     * Action routing map - maps machine slugs to their respective service categories
     * This provides explicit documentation of available actions and improves maintainability.
     */
    private const ACTION_SERVICE_MAP = [
        // Order Events
        'getAllOrder'             => 'OrderService',
        'getOrderById'            => 'OrderService',
        'getTotalPaidAmount'      => 'OrderService',
        'getTotalRefundAmount'    => 'OrderService',
        'getLatestTransaction'    => 'OrderService',
        'getCurrentSubscription'  => 'OrderService',
        'generateReceiptNumber'   => 'OrderService',
        'getReceiptUrl'           => 'OrderService',
        'getParentOrder'          => 'OrderService',
        'getChildOrder'           => 'OrderService',
        'getOrderTransactions'    => 'OrderService',
        'getOrderSubscriptions'   => 'OrderService',
        'getOrderItems'           => 'OrderService',
        'getOrderCustomer'        => 'OrderService',
        'getOrderMetadata'        => 'OrderService',
        'getOrderMetadataByKey'   => 'OrderService',
        'updateOrderMetadata'     => 'OrderService',
        'deleteOrderMetadata'     => 'OrderService',
        'getOrderCoupons'         => 'OrderService',
        'getOrderShippingAddress' => 'OrderService',
        'getOrderBillingAddress'  => 'OrderService',
        'getOrderAddresses'       => 'OrderService',
        'getOrderLicenses'        => 'OrderService',
        'getOrderLabels'          => 'OrderService',
        'getOrderRenewals'        => 'OrderService',
        'getOrderTaxRates'        => 'OrderService',
        'updateOrderStatus'       => 'OrderService',
        'updatePaymentStatus'     => 'OrderService',
        'updateShippingStatus'    => 'OrderService',
        'createOrder'             => 'OrderService',
        'updateOrder'             => 'OrderService',
        'deleteOrder'             => 'OrderService',

        // Order Transaction Events
        'getAllTransaction'           => 'OrderTransactionService',
        'getTransactionById'          => 'OrderTransactionService',
        'getRefundTransactions'       => 'OrderTransactionService',
        'getSubscriptionTransactions' => 'OrderTransactionService',

        // Customer Events
        'getAllCustomer'                    => 'CustomerService',
        'getCustomerById'                   => 'CustomerService',
        'getCustomerOrders'                 => 'CustomerService',
        'getCustomerSubscriptions'          => 'CustomerService',
        'getCustomerShippingAddress'        => 'CustomerService',
        'getCustomerBillingAddress'         => 'CustomerService',
        'getCustomerPrimaryShippingAddress' => 'CustomerService',
        'getCustomerPrimaryBillingAddress'  => 'CustomerService',
        'getCustomerMetadata'               => 'CustomerService',
        'getCustomerLabels'                 => 'CustomerService',
        'createCustomer'                    => 'CustomerService',
        'updateCustomer'                    => 'CustomerService',
        'deleteCustomer'                    => 'CustomerService',

        // Product Events
        'getAllProduct'      => 'ProductService',
        'getProductById'     => 'ProductService',
        'getProductVariants' => 'ProductService',
        'createProduct'      => 'ProductService',
        'deleteProduct'      => 'ProductService',
        // Coupon Events
        'getAllCoupon'  => 'CouponService',
        'getCouponById' => 'CouponService',
        'createCoupon'  => 'CouponService',
        'deleteCoupon'  => 'CouponService',

        // License Events
        'getAllLicense'         => 'LicenseService',
        'getLicenseById'        => 'LicenseService',
        'getCustomerLicenses'   => 'LicenseService',
        'getExpiringLicenses'   => 'LicenseService',
        'generateNewLicenseKey' => 'LicenseService',
        'suspendLicense'        => 'LicenseService',
        'unsuspendLicense'      => 'LicenseService',
    ];

    private $nodeInfoProvider;

    public function __construct(NodeInfoProvider $nodeInfoProvider)
    {
        $this->nodeInfoProvider = $nodeInfoProvider;
    }

    public function execute(): array
    {
        $executedNodeAction = $this->executeFluentCartAction();

        return Utility::formatResponseData(
            $executedNodeAction['status_code'] ?? 200,
            $executedNodeAction['payload'] ?? [],
            $executedNodeAction['response'] ?? []
        );
    }

    /**
     * Get the service class for a given action.
     *
     * @param string $machineSlug The action machine slug
     *
     * @return null|string The service class or null if not found
     */
    private static function getServiceClass(string $machineSlug): ?string
    {
        return self::ACTION_SERVICE_MAP[$machineSlug] ?? null;
    }

    private function executeFluentCartAction()
    {
        if (!\defined('FLUENTCART_PLUGIN_PATH')) {
            return [
                'status_code' => 400,
                'payload'     => [],
                'response'    => __('FluentCart plugin is not active.', 'bit-pi'),
            ];
        }

        $machineSlug = $this->nodeInfoProvider->getMachineSlug();
        if (empty($machineSlug)) {
            return [
                'status_code' => 400,
                'payload'     => [],
                'response'    => __('Action method is required.', 'bit-pi'),
            ];
        }

        $className = self::getServiceClass($machineSlug);
        if (!$className) {
            return [
                'status_code' => 400,
                'payload'     => [],
                'response'    => \sprintf(
                    // translators: %s: action method name
                    __('FluentCart action "%s" is not registered.', 'bit-pi'),
                    $machineSlug
                ),
            ];
        }

        $serviceClass = '\BitApps\PiPro\src\Integrations\FluentCart\Services\\' . $className;

        $fluentCartServices = new $serviceClass($this->nodeInfoProvider);

        return $fluentCartServices->{$machineSlug}();
    }
}
