<?php

namespace common\logic\User\UserProducer\Repository;

use common\logic\AbstractRepository;
use common\logic\Producer\Producer\Model\Producer;
use common\logic\User\User\Model\User;
use common\logic\User\UserProducer\Model\UserProducer;

class UserProducerRepository extends AbstractRepository
{
    protected UserProducerRepositoryQuery $query;

    public function loadDependencies(): void
    {
        $this->loadQuery(UserProducerRepositoryQuery::class);
    }

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

    public function findOneUserProducer(User $user)
    {
        return $this->createDefaultQuery()
            ->filterByUser($user)
            ->findOne();
    }

    public function findUserProducersByUser(User $user, bool $active = true, bool $bookmark = true)
    {
        return $this->createQuery()
            ->filterByUser($user)
            ->filterByActive($active)
            ->filterByBookmark($bookmark)
            ->find();
    }

    public function isProducerBookmarked(User $user): bool
    {
        $userProducer = $this->findOneUserProducer($user);
        return $userProducer ? $userProducer->bookmark : false;
    }

    public function findUserProducersWithNegativeOrPositiveCredit()
    {
        return $this->createDefaultQuery()
            ->filterHasNegativeOrPositiveCredit()
            ->find();
    }

    public function sumUserProducerCredits()
    {
        $sumUserProducersCredits = 0;
        $userProducersWithNegativeOrPositiveCreditArray = $this->findUserProducersWithNegativeOrPositiveCredit();

        foreach ($userProducersWithNegativeOrPositiveCreditArray as $userProducerWithNegativeOrPositiveCredit) {
            $sumUserProducersCredits += $userProducerWithNegativeOrPositiveCredit->credit;
        }

        return $sumUserProducersCredits;
    }
}