<?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 = [
        'commission_enabled',
        'commission_percent',
        'site_name',
        'support_phone',
        'max_cancel_hours_before',
        'appointment_reminder_hours',
        // payment gateways
        'payment_test_mode',
        'payment_allowed_frontend_hosts',
        'mellat_terminal_id',
        'mellat_username',
        'mellat_password',
        'sep_terminal_id',
        // sms provider
        'sms_provider',
        'kavenegar_api_key',
        'kavenegar_sender',
        'rangineh_api_key',
        'rangineh_sender',
        'sms_price_rials',
    ];

    public function __construct(
        private readonly SiteConfigRepository  $configRepo,
        private readonly EntityManagerInterface $em,
    ) {}

    #[Route('/api/v1/admin/settings', methods: ['GET'])]
    public function get(): JsonResponse
    {
        return $this->success($this->configRepo->getAll());
    }

    #[Route('/api/v1/admin/settings', methods: ['PATCH'])]
    public function patch(Request $request): JsonResponse
    {
        $data = json_decode($request->getContent(), true) ?? [];

        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();

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