<?php

namespace App\Handlers;

use App\Models\TelegramCustomer;
use Carbon\Carbon;
use Symfony\Component\HttpFoundation\JsonResponse;
use Openguru\OpenCartFramework\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Openguru\OpenCartFramework\Support\Arr;
use Openguru\OpenCartFramework\Telegram\Enums\TelegramHeader;
use Openguru\OpenCartFramework\Telegram\TelegramService;
use Psr\Log\LoggerInterface;

class PrivacyPolicyHandler
{
    private TelegramService $telegramService;
    private TelegramCustomer $telegramCustomer;
    private LoggerInterface $logger;

    public function __construct(
        TelegramService $telegramService,
        TelegramCustomer $telegramCustomer,
        LoggerInterface $logger
    ) {
        $this->telegramService = $telegramService;
        $this->telegramCustomer = $telegramCustomer;
        $this->logger = $logger;
    }

    public function checkIsUserPrivacyConsented(Request $request): JsonResponse
    {
        $isPrivacyConsented = false;
        $telegramUserId = $this->telegramService->userId($request->header(TelegramHeader::INIT_DATA));

        if (! $telegramUserId) {
            return new JsonResponse([
                'data' => [
                    'is_privacy_consented' => false,
                ],
            ]);
        }

        $customer = $this->telegramCustomer->findByTelegramUserId($telegramUserId);

        if ($customer) {
            $isPrivacyConsented = Arr::get($customer, 'privacy_consented_at') !== null;
        }

        return new JsonResponse([
            'data' => [
                'is_privacy_consented' => $isPrivacyConsented,
            ],
        ]);
    }

    public function userPrivacyConsent(Request $request): JsonResponse
    {
        $telegramUserId = $this->telegramService->userId($request->header(TelegramHeader::INIT_DATA));

        if ($telegramUserId) {
            $this->telegramCustomer->updateByTelegramUserId($telegramUserId, [
                'privacy_consented_at' => Carbon::now()->toDateTimeString(),
            ]);
        } else {
            $this->logger->warning(
                'Could not find customer with telegram user_id: ' . $telegramUserId . ' to give privacy consent.'
            );
        }

        return new JsonResponse([], Response::HTTP_NO_CONTENT);
    }
}
