<?php

namespace App\Traits;

use App\Enums\PaymentStatusEnum;
use App\Models\Deposit;
use App\Models\Payment;
use App\Services\Quiz\QuizDepositPayment;

trait PaymentHelper
{
    public function isDatabaseAlreadyUpdated(Payment $payment)
    {
        return $payment->status !== PaymentStatusEnum::PENDING;
    }

    public function updatePaymentStatus(Payment $payment, PaymentStatusEnum $status = PaymentStatusEnum::PAID)
    {
        $payment->status = $status;
        $payment->save();
    }

    public function quizDepositHandler(Payment $payment, PaymentStatusEnum $status)
    {
        $deposit_payment = new QuizDepositPayment;

        $deposit = $this->getDeposit($payment);

        if (! $deposit) {
            throw new \InvalidArgumentException('Deposit not found');
        }

        switch ($status) {
            case PaymentStatusEnum::PAID:
                $deposit_payment->depositConfirmed($deposit);
                break;
            case PaymentStatusEnum::CANCELLED:
                $deposit_payment->depositCancelled($deposit);
                break;
            case PaymentStatusEnum::FAILED:
                $deposit_payment->depositFailed($deposit);
                break;
            default:
                break;
        }

    }

    private function getDeposit(Payment $payment): ?Deposit
    {
        return $payment->deposit()->first();
    }

    public function updatePaidPayment(Payment $payment)
    {
        $this->quizDepositHandler($payment, PaymentStatusEnum::PAID);

        $this->updatePaymentStatus($payment, PaymentStatusEnum::PAID);
    }

    public function updateCancelledPayment(Payment $payment)
    {
        $this->quizDepositHandler($payment, PaymentStatusEnum::CANCELLED);

        $this->updatePaymentStatus($payment, PaymentStatusEnum::CANCELLED);
    }

    public function updateFailedPayment(Payment $payment)
    {
        $this->quizDepositHandler($payment, PaymentStatusEnum::FAILED);

        $this->updatePaymentStatus($payment, PaymentStatusEnum::FAILED);
    }
}
