<?php

declare(strict_types=1);

namespace KupShop\SalesBundle\View;

use KupShop\KupShopBundle\Context\UserContext;
use KupShop\KupShopBundle\Exception\RedirectException;
use KupShop\KupShopBundle\Util\Contexts;
use KupShop\KupShopBundle\Views\View;
use KupShop\SalesBundle\Entity\Sale;
use KupShop\SalesBundle\Util\SalesUtil;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class SaleView extends View
{
    protected $template = 'sales/sale.tpl';

    private int $saleId;
    private ?string $securityCode;

    private ?Sale $sale = null;

    public function __construct(
        private readonly SalesUtil $salesUtil,
    ) {
    }

    public function getTitle()
    {
        return sprintf(translate('saleDetail', 'sales'), $this->getSale()?->code);
    }

    public function setSaleId(int $saleId): self
    {
        $this->saleId = $saleId;

        return $this;
    }

    public function setSecurityCode(?string $securityCode): self
    {
        $this->securityCode = $securityCode;

        return $this;
    }

    public function getResponse(?Request $request = null)
    {
        if (!$this->checkSaleOwnership()) {
            throw new RedirectException(path('kupshop_user_login_login'));
        }

        return parent::getResponse($request);
    }

    public function getBodyVariables()
    {
        $vars = parent::getBodyVariables();

        $vars['sale'] = SalesUtil::wrapSales($this->getSale());

        return $vars;
    }

    private function checkSaleOwnership(): bool
    {
        $userId = Contexts::get(UserContext::class)->getActiveId();

        if ($userId && $userId == $this->getSale()->userId) {
            return true;
        }

        if ($this->securityCode && $this->securityCode === $this->salesUtil->getSaleSecurityCode($this->getSale())) {
            return true;
        }

        return false;
    }

    private function getSale(): ?Sale
    {
        if (!$this->sale) {
            if (!($this->sale = $this->salesUtil->getSale($this->saleId))) {
                throw new NotFoundHttpException('Sale not found');
            }

            $this->sale->productCollection->fetchMainImages(2);
        }

        return $this->sale;
    }
}
