<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\CoreBundle\Facade;

use Doctrine\Common\Collections\Criteria;
use Doctrine\ORM\QueryBuilder;
use Ferienpass\CoreBundle\Entity\Attendance;
use Ferienpass\CoreBundle\Entity\User;
use Ferienpass\CoreBundle\Repository\AttendanceRepository;

class PaymentsFacade
{
    public function __construct(private readonly AttendanceRepository $attendances)
    {
    }

    /** @return Attendance[] */
    public function attendancesDue(?User $user = null): array
    {
        $qb = $this->attendances->createQueryBuilder('attendance')
            ->select('attendance', 'participant')
            ->innerJoin('attendance.participant', 'participant')
        ;

        self::addWhereLogic($qb);

        if ($user instanceof User) {
            $qb
                ->andWhere('participant.user = :user')
                ->setParameter('user', $user->getId())
            ;
        }

        return $qb
            ->getQuery()
            ->getResult()
        ;
    }

    public static function addWhereLogic(QueryBuilder $queryBuilder): void
    {
        $queryBuilder
            ->andWhere('attendance.paid <> 1')
            ->andWhere('attendance.payable <> 0')
        ;

        self::addUsePaymentsLogic($queryBuilder);
    }

    /**
     * Drop attendances belonging to a season that doesn't collect fees
     * ({@see Attendance::usesPayments()}) — those have no pay status, so they
     * must not show up anywhere money is owed.
     *
     * The offer is joined under its own aliases rather than reusing whatever the
     * caller joined, so this stays a drop-in for any query over `attendance`.
     * An offer without a season keeps its rows.
     */
    public static function addUsePaymentsLogic(QueryBuilder $queryBuilder): void
    {
        $queryBuilder
            ->leftJoin('attendance.offer', 'offer_usePayments')
            ->leftJoin('offer_usePayments.edition', 'edition_usePayments')
            ->andWhere('attendance.offer IS NULL OR offer_usePayments.edition IS NULL OR edition_usePayments.usePayments = 1')
        ;
    }

    /**
     * Narrow a query over attendances to those that must never be billed: their
     * offer charges nothing, or it does not collect its fee online.
     *
     * This is the DQL twin of the guard in
     * {@see \Ferienpass\CoreBundle\EventListener\Workflow\AttendanceConfirmTransactionListener},
     * for the paths that write `payable` in bulk (committing staged
     * confirmations) — there no entity is loaded, so no workflow listener runs
     * and the rule has to be repeated in SQL. Both must agree: whether an
     * attendance ends up billed may not depend on the route it took.
     *
     * The offer is joined under an alias derived from the caller's, so the query
     * can be embedded as a subquery of another one.
     */
    public static function addUnbillableLogic(QueryBuilder $queryBuilder, string $alias = 'attendance'): void
    {
        $queryBuilder
            ->innerJoin($alias.'.offer', $offer = $alias.'_unbillable')
            ->andWhere(\sprintf('%1$s.disableOnlinePayment = true OR %1$s.fee IS NULL OR %1$s.fee = 0', $offer))
        ;
    }

    public static function addCriteria(Criteria $criteria): void
    {
        $expr = Criteria::expr();

        $criteria
            ->andWhere($expr->eq('paid', false))
            ->andWhere($expr->eq('payable', true))
        ;
    }
}
