<?php

namespace App\Service;

use App\Entity\Advert;
use App\Entity\Devis;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;

class AdvertService
{
    public function __construct(
        private OrderNumberService $orderNumberService,
        private EntityManagerInterface $em,
        #[Autowire('%env(APP_SECRET)%')] private string $hmacSecret,
        #[Autowire(env: 'TVA_ENABLED')] private string $tvaEnabled = 'false',
        #[Autowire(env: 'TVA_RATE')] private string $tvaRate = '0.20',
    ) {
    }

    public function isTvaEnabled(): bool
    {
        return 'true' === $this->tvaEnabled || '1' === $this->tvaEnabled;
    }

    public function getTvaRate(): float
    {
        return (float) $this->tvaRate;
    }

    public function create(?Devis $devis = null): Advert
    {
        $orderNumber = null !== $devis
            ? $devis->getOrderNumber()
            : $this->orderNumberService->generateAndUse();

        $advert = new Advert($orderNumber, $this->hmacSecret);

        if (null !== $devis) {
            $advert->setDevis($devis);
        }

        $this->em->persist($advert);
        $this->em->flush();

        return $advert;
    }

    public function createFromDevis(Devis $devis): Advert
    {
        return $this->create($devis);
    }

    /**
     * Calcule les totaux selon la config TVA.
     *
     * @return array{totalHt: string, totalTva: string, totalTtc: string}
     */
    public function computeTotals(string $totalHt): array
    {
        $ht = (float) $totalHt;

        if ($this->isTvaEnabled()) {
            $tva = round($ht * $this->getTvaRate(), 2);
            $ttc = round($ht + $tva, 2);
        } else {
            $tva = 0.0;
            $ttc = $ht;
        }

        return [
            'totalHt' => number_format($ht, 2, '.', ''),
            'totalTva' => number_format($tva, 2, '.', ''),
            'totalTtc' => number_format($ttc, 2, '.', ''),
        ];
    }
}
