<?php

namespace domain\PointSale\UserPointSale;

use domain\Distribution\Distribution\Distribution;
use domain\PointSale\PointSale\PointSale;
use domain\PointSale\PointSale\PointSaleSolver;
use domain\User\User\User;
use domain\_\AbstractRepository;

class UserPointSaleRepository extends AbstractRepository
{
    protected UserPointSaleRepositoryQuery $query;
    protected PointSaleSolver $pointSaleSolver;

    public function loadDependencies(): void
    {
        $this->loadQuery(UserPointSaleRepositoryQuery::class);
        $this->pointSaleSolver = $this->loadService(PointSaleSolver::class);
    }

    public function getDefaultOptionsSearch(): array
    {
        return [
            self::WITH => [],
            self::JOIN_WITH => [],
            self::ORDER_BY => '',
            self::ATTRIBUTE_ID_PRODUCER => 'point_sale.id_producer'
        ] ;
    }

    public function findUserPointSalesByUser(User $user, Distribution $distribution = null): array
    {
        $userPointSalesArray = $this->createDefaultQuery()
            ->joinPointSale()
            ->filterByUser($user)
            ->find();

        if($distribution) {
            $userPointSalesArray = $this->pointSaleSolver->filterUserPointSalesByDistribution($userPointSalesArray, $distribution);
        }

        return $userPointSalesArray;
    }

    public function findOneUserPointSale(User $user = null, PointSale $pointSale = null)
    {
        if(!$user || !$pointSale) {
            return null;
        }

        return $this->createDefaultQuery()
            ->joinPointSale()
            ->filterByUser($user)
            ->filterByPointSale($pointSale)
            ->findOne();
    }
}