<?php

namespace App\Domains\Event\Actions\ParticipantPayment;

use App\Mail\ParticipantPaymentMails\ParticipantPaymentMissingPaymentMail;
use App\Mail\ParticipantPaymentMails\ParticipantPaymentOverpaidMail;
use App\Mail\ParticipantPaymentMails\ParticipantPaymentPaidMail;
use App\Providers\MissingPaymentProvider;
use Illuminate\Support\Facades\Mail;

class ParticipantPaymentCommand {
    public function __construct(public ParticipantPaymentRequest $request) {
    }

    public function execute() : ParticipantPaymentResponse {
        $response = new ParticipantPaymentResponse();

        $this->request->participant->amount_paid = $this->request->amountPaid;
        $this->request->participant->save();

        $response->amountPaid = $this->request->participant->amount_paid;
        $response->amountExpected = $this->request->participant->amount;

        $amountToPay = MissingPaymentProvider::calculateMissingPayment(
            amountPaid: $this->request->participant->amount_paid,
            amountToPay: $this->request->participant->amount,
        );

        switch (true) {
            case $amountToPay->getAmount() > 0:
                Mail::to($this->request->participant->email_1)->send(new ParticipantPaymentMissingPaymentMail(
                    participant: $this->request->participant,
                ));

                if ($this->request->participant->email_2 !== null) {
                    Mail::to($this->request->participant->email_2)->send(new ParticipantPaymentMissingPaymentMail(
                        participant: $this->request->participant,
                    ));
                }
                break;
            case $amountToPay->getAmount() < 0:
                Mail::to($this->request->participant->email_1)->send(new ParticipantPaymentOverpaidMail(
                    participant: $this->request->participant,
                ));

                if ($this->request->participant->email_2 !== null) {
                    Mail::to($this->request->participant->email_2)->send(new ParticipantPaymentOverpaidMail(
                        participant: $this->request->participant,
                    ));
                }
                break;
            default:
                Mail::to($this->request->participant->email_1)->send(new ParticipantPaymentPaidMail(
                    participant: $this->request->participant,
                ));

                if ($this->request->participant->email_2 !== null) {
                    Mail::to($this->request->participant->email_2)->send(new ParticipantPaymentPaidMail(
                        participant: $this->request->participant,
                    ));
                }
        }

        $response->participant = $this->request->participant;
        $response->success = true;

        return $response;
    }
}
