<?php
/**
 * 2026 Paysera
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@prestashop.com so we can send you a copy immediately.
 *
 * @author Paysera <plugins@paysera.com>
 * @copyright 2026 Paysera
 * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
 * International Registered Trademark & Property of Paysera
 */

declare(strict_types=1);

namespace Paysera\PrestashopPayments\Installer;

use Paysera\PrestashopPayments\Dto\OrderStatusDto;
use Paysera\PrestashopPayments\Enum\ConfigurationKey;
use Psr\Log\LoggerInterface;

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

class OrderStatusInstaller
{
    private const COLOR_AWAITING = '#4169E1';
    private const COLOR_PENDING = '#FFA500';

    public function __construct(
        private LoggerInterface $logger
    ) {
    }

    public function install(): void
    {
        $this->logger->debug('Installing Paysera custom order statuses');

        $statuses = $this->getOrderStatusDefinitions();
        $this->logger->debug('Status definitions retrieved', [
            'count' => count($statuses),
        ]);

        foreach ($statuses as $status) {
            $this->createOrderStatus($status);
        }

        $this->logger->info('Paysera custom order statuses installed successfully');
    }

    private function getOrderStatusDefinitions(): array
    {
        return [
            new OrderStatusDto(
                configKey: ConfigurationKey::STATUS_AWAITING_PAYMENT,
                names: [
                    'en' => 'Awaiting Paysera Payment',
                    'lt' => 'Laukiama Paysera mokėjimo',
                ],
                color: self::COLOR_PENDING,
                delivery: true,
            ),
            new OrderStatusDto(
                configKey: ConfigurationKey::STATUS_AWAITING_CONFIRMATION,
                names: [
                    'en' => 'Awaiting Paysera Confirmation',
                    'lt' => 'Laukiama Paysera patvirtinimo',
                ],
                color: self::COLOR_AWAITING,
            ),
        ];
    }

    private function createOrderStatus(OrderStatusDto $dto): void
    {
        $this->logger->debug('Creating order status', [
            'config_key' => $dto->configKey,
        ]);

        $existingStatusId = $this->findExistingOrderStatus($dto->configKey);

        if ($existingStatusId !== null) {
            $this->reuseExistingStatus($dto->configKey, $existingStatusId);

            return;
        }

        $this->createNewOrderStatus($dto);
    }

    private function reuseExistingStatus(string $configKey, int $statusId): void
    {
        $customKey = $this->getCustomOrderStatusKey($configKey);
        \Configuration::updateValue($customKey, $statusId);
        \Configuration::updateValue($configKey, $statusId);

        $this->logger->debug('Order status already exists, reusing', [
            'config_key' => $configKey,
            'custom_key' => $customKey,
            'status_id' => $statusId,
        ]);
    }

    private function createNewOrderStatus(OrderStatusDto $dto): void
    {
        $orderState = $this->buildOrderState($dto);
        $this->setOrderStateNames($orderState, $dto);

        if (!$orderState->add()) {
            $this->logger->error('Failed to create order status', [
                'config_key' => $dto->configKey,
            ]);
            throw new \Exception('Failed to add OrderState for ' . $dto->configKey);
        }

        $this->saveOrderStatusConfiguration($dto->configKey, (int) $orderState->id);
    }

    private function buildOrderState(OrderStatusDto $dto): \OrderState
    {
        $orderState = new \OrderState();
        $orderState->send_email = $dto->sendEmail;
        $orderState->module_name = 'payserapayments';
        $orderState->invoice = $dto->invoice;
        $orderState->color = $dto->color;
        $orderState->logable = $dto->logable;
        $orderState->shipped = $dto->shipped;
        $orderState->unremovable = true;
        $orderState->delivery = $dto->delivery;
        $orderState->hidden = $dto->hidden;
        $orderState->paid = $dto->paid;
        $orderState->pdf_invoice = $dto->pdfInvoice;

        return $orderState;
    }

    private function setOrderStateNames(\OrderState $orderState, OrderStatusDto $dto): void
    {
        $languages = \Language::getLanguages(false);

        foreach ($languages as $language) {
            $langCode = strtolower($language['iso_code']);
            $idLang = (int) $language['id_lang'];

            $orderState->name[$idLang] = $dto->names[$langCode] ?? $dto->names['en'];

            if ($dto->sendEmail && $dto->template !== '') {
                $orderState->template[$idLang] = $dto->template;
            }
        }
    }

    private function saveOrderStatusConfiguration(string $configKey, int $statusId): void
    {
        $customKey = $this->getCustomOrderStatusKey($configKey);

        \Configuration::updateValue($customKey, $statusId);
        \Configuration::updateValue($configKey, $statusId);

        $this->logger->debug('Created order status', [
            'config_key' => $configKey,
            'custom_key' => $customKey,
            'status_id' => $statusId,
        ]);
    }

    private function findExistingOrderStatus(string $statusKey): ?int
    {
        $customKey = $this->getCustomOrderStatusKey($statusKey);

        $statusId = (int) \Configuration::get($customKey);
        if ($statusId === 0) {
            $statusId = (int) \Configuration::get($statusKey);
        }

        if ($statusId === 0) {
            return null;
        }

        $orderState = new \OrderState($statusId);
        if (!$orderState->id) {
            $this->logger->warning('Status ID found in config but does not exist in database', [
                'status_key' => $statusKey,
                'custom_key' => $customKey,
                'status_id' => $statusId,
            ]);

            return null;
        }

        return (int) $orderState->id;
    }

    private function getCustomOrderStatusKey(string $statusKey): string
    {
        return match ($statusKey) {
            ConfigurationKey::STATUS_AWAITING_PAYMENT => ConfigurationKey::CUSTOM_OS_AWAITING_PAYMENT,
            ConfigurationKey::STATUS_AWAITING_CONFIRMATION => ConfigurationKey::CUSTOM_OS_AWAITING_CONFIRMATION,
            default => $statusKey,
        };
    }
}
