<?php

namespace BitApps\PiPro\src\Integrations\FluentCart\Services;

use BitApps\Pi\src\Flow\NodeInfoProvider;
use BitApps\PiPro\src\Integrations\FluentCart\FluentCartHelper;
use FluentCart\App\Models\Customer;
use FluentCartPro\App\Modules\Licensing\Models\License;

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

final class LicenseService
{
    private $nodeInfoProvider;

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

    public function getAllLicense(): array
    {
        if ($validationResponse = FluentCartHelper::validateClassExistence('license')) {
            return $validationResponse;
        }

        $licenses = License::all();
        $data = ['licenses' => FluentCartHelper::prepareData($licenses)];

        return [
            'response'    => $data,
            'payload'     => [],
            'status_code' => 200
        ];
    }

    public function getLicenseById(): array
    {
        $license = $this->validateAndGetLicense(
            [
                'customer',
                'product',
                'order',
                'activations',
            ]
        );

        if (!$license instanceof License) {
            return $license;
        }

        return [
            'response'    => FluentCartHelper::prepareData($license),
            'payload'     => [],
            'status_code' => 200
        ];
    }

    public function getCustomerLicenses(): array
    {
        if ($validationError = FluentCartHelper::validateClassExistence('customer')) {
            return $validationError;
        }

        $fieldMappings = $this->nodeInfoProvider->getFieldMapData();
        $rules = ['id' => ['required', 'integer']];

        if ($validationError = FluentCartHelper::validateFieldMap($fieldMappings, $rules)) {
            return $validationError;
        }

        $customer = Customer::find($fieldMappings['id']);

        if (!$customer) {
            return [
                'response'    => __('Customer not found.', 'bit-pi'),
                'payload'     => [],
                'status_code' => 404
            ];
        }

        $licenses = $customer->licenses()->get();

        return [
            'response'    => FluentCartHelper::prepareData($licenses),
            'payload'     => [],
            'status_code' => 200
        ];
    }

    public function getExpiringLicenses(): array
    {
        if ($validationResponse = FluentCartHelper::validateClassExistence('license')) {
            return $validationResponse;
        }

        $licenses = License::expiringSoon(7)->active()->get();
        $data = ['licenses' => FluentCartHelper::prepareData($licenses)];

        return [
            'response'    => $data,
            'payload'     => [],
            'status_code' => 200
        ];
    }

    public function generateNewLicenseKey(): array
    {
        $license = $this->validateAndGetLicense(
            [
                'customer',
                'product',
                'order',
                'activations',
            ]
        );

        if (!$license instanceof License) {
            return $license;
        }

        $data = [
            'new_license_key' => $license->generateLicenseKey(),
        ];

        return [
            'response'    => $data,
            'payload'     => [],
            'status_code' => 200
        ];
    }

    public function suspendLicense(): array
    {
        $license = $this->validateAndGetLicense(
            [
                'customer',
                'product',
                'order',
                'activations',
            ]
        );

        if (!$license instanceof License) {
            return $license;
        }

        if (!$license->suspend()) {
            return [
                'response'    => __('Failed to suspend the license.', 'bit-pi'),
                'payload'     => [],
                'status_code' => 500
            ];
        }

        return [
            'response'    => __('License suspended successfully.', 'bit-pi'),
            'payload'     => [],
            'status_code' => 200
        ];
    }

    public function unsuspendLicense(): array
    {
        $license = $this->validateAndGetLicense(
            [
                'customer',
                'product',
                'order',
                'activations',
            ]
        );

        if (!$license instanceof License) {
            return $license;
        }

        if (!$license->unsuspend()) {
            return [
                'response'    => __('Failed to unsuspend the license.', 'bit-pi'),
                'payload'     => [],
                'status_code' => 500
            ];
        }

        return [
            'response'    => __('License unsuspended successfully.', 'bit-pi'),
            'payload'     => [],
            'status_code' => 200
        ];
    }

    /**
     * Validate and get License.
     */
    private function validateAndGetLicense(array $relations = []): array|License
    {
        if ($validationError = FluentCartHelper::validateClassExistence('license')) {
            return $validationError;
        }

        $fieldMappings = $this->nodeInfoProvider->getFieldMapData();
        $rules = ['id' => ['required', 'integer']];

        if ($validationError = FluentCartHelper::validateFieldMap($fieldMappings, $rules)) {
            return $validationError;
        }

        if (empty($relations)) {
            $license = License::find($fieldMappings['id']);
        } else {
            $license = License::with($relations)->find($fieldMappings['id']);
        }

        if (!$license) {
            return [
                'response'    => __('License not found.', 'bit-pi'),
                'payload'     => [],
                'status_code' => 404
            ];
        }

        return $license;
    }
}
