<?php

namespace App\Config\Controller;

use App\Config\Repository\SiteConfigRepository;
use App\Shared\Controller\BaseController;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
use OpenApi\Attributes as OA;

#[OA\Tag(name: 'Config')]
#[IsGranted('ROLE_ADMIN')]
class SiteConfigController extends BaseController
{
    private const ALLOWED_KEYS = [
        // financial engine
        'appointment_commission_enabled',
        'upgrade_commission_enabled',
        'upgrade_commission_percent',
        'tax_enabled',
        'tax_percent',
        'sms_panel_fee_rials',
        'sms_price_rials',
        'appointment_fee_rials',
        'site_name',
        'support_phone',
        'max_cancel_hours_before',
        'appointment_reminder_hours',
        'log_retention_days',
        // captcha
        'altcha_enabled',
        // payment gateways
        'payment_test_mode',
        'payment_allowed_frontend_hosts',
        'mellat_enabled',
        'mellat_sandbox',
        'mellat_wsdl_url',
        'mellat_terminal_id',
        'mellat_username',
        'mellat_password',
        'sep_enabled',
        'sep_terminal_id',
    ];

    public function __construct(
        private readonly SiteConfigRepository  $configRepo,
        private readonly \App\Config\Repository\TaxRateHistoryRepository $taxHistoryRepo,
        private readonly EntityManagerInterface $em,
        private readonly \App\Shared\Captcha\AltchaService $altcha,
    ) {}

    #[Route('/api/v1/admin/settings', methods: ['GET'])]
    public function get(): JsonResponse
    {
        $config = $this->configRepo->getAll();
        // کلید API پیامک فقط از env؛ فقط وضعیت تنظیم‌بودن برگردانده می‌شود نه مقدار.
        $config['sms_api_key_configured'] = ($_ENV['KAVENEGAR_API_KEY'] ?? '') !== '';
        // مقدار مؤثر کپچا (override پنل اگر ست شده، وگرنه env) تا toggle درست نمایش دهد.
        $config['altcha_enabled'] = $this->altcha->enabled() ? '1' : '0';
        return $this->success($config);
    }

    #[Route('/api/v1/admin/settings', methods: ['PATCH'])]
    public function patch(Request $request, #[\Symfony\Component\Security\Http\Attribute\CurrentUser] \App\Auth\Entity\User $admin): JsonResponse
    {
        $data = json_decode($request->getContent(), true) ?? [];

        // مقادیر فعلی مالیات برای تشخیص تغییر و ثبت تاریخچه.
        $prevTaxPercent = $this->configRepo->get('tax_percent');
        $prevTaxEnabled = $this->configRepo->get('tax_enabled');

        foreach ($data as $key => $value) {
            if (!in_array($key, self::ALLOWED_KEYS, true)) {
                continue;
            }
            $this->configRepo->set($key, $value === null ? null : (string) $value);
        }

        $this->em->flush();

        $newTaxPercent = $this->configRepo->get('tax_percent');
        $newTaxEnabled = $this->configRepo->get('tax_enabled');

        if ($newTaxPercent !== $prevTaxPercent || $newTaxEnabled !== $prevTaxEnabled) {
            $this->taxHistoryRepo->save(new \App\Config\Entity\TaxRateHistory(
                (string) $newTaxPercent,
                $newTaxEnabled === '1',
                $admin,
            ));
        }

        return $this->success($this->configRepo->getAll());
    }

    #[Route('/api/v1/admin/settings/tax-history', methods: ['GET'])]
    public function taxHistory(): JsonResponse
    {
        $rows = $this->taxHistoryRepo->findBy([], ['changedAt' => 'DESC'], 50);

        return $this->success(array_map(
            fn(\App\Config\Entity\TaxRateHistory $h) => $h->toArray(),
            $rows,
        ));
    }
}
