<?php

namespace App\Classes\Modules\Transactions\ControllersLogic;

use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Transactions\Services\FetchesBillGroup;
use App\Classes\Modules\Transactions\Services\DeletesTransaction;
use App\Classes\Modules\Transactions\Services\UpdatesTransactionStatus;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Http\Resources\BillGroupResource;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class DeleteBillGroupLogic extends AbstractControllerLogic
{

    /**
     * @return array
     */
    protected function notification():array {
        return [
            'title' => 'Delete Bill Group Transaction',
            'message' => 'You have successfully deleted this Bill Group Transaction'
        ];
    }

    /** @var FetchesBillGroup */
    private $fetchesBillGroup;

    /** @var DeletesTransaction */
    private $deletesTransaction;

    /** @var UpdatesTransactionStatus */
    private $updatesTransactionStatus;

    /**
     * DeleteBillGroupLogic constructor.
     * @param FetchesBillGroup $fetchesBillGroup
     * @param DeletesTransaction $deletesTransaction
     * @param UpdatesTransactionStatus $updatesTransactionStatus
     */
    public function __construct(FetchesBillGroup $fetchesBillGroup, DeletesTransaction $deletesTransaction, UpdatesTransactionStatus $updatesTransactionStatus)
    {
        $this->fetchesBillGroup = $fetchesBillGroup;
        $this->deletesTransaction = $deletesTransaction;
        $this->updatesTransactionStatus = $updatesTransactionStatus;
    }

    /**
     * @param Request $request
     * @return JsonResponse
     * @throws \App\Classes\Exceptions\MalformedRequestException
     */
    public function logic(Request $request) : JsonResponse
    {
        $billGroup = $this->fetchesBillGroup->execute(['id' => $request->route('id')]);

        $transactions = $billGroup->transactions()->get();

        foreach($transactions as $transaction) {
            $this->deletesTransaction->execute($transaction);
        }

        $groups = $billGroup->groups()->get();

        foreach($groups as $group) {
            $billGroup->groups()->detach($group->id);
        }
        
        $billRefunds = $billGroup->billRefunds()->get();

        foreach($billRefunds as $billRefund) {
            $billGroup->billRefunds()->detach($billRefund->id);
            $this->deletesTransaction->execute($billRefund);
            $this->updatesTransactionStatus->execute($billRefund->owner, ApprovalStatus::APPROVED);
        }
        
        $billGroup->delete();
        
        return $this->resourceResponse(new BillGroupResource($billGroup));
    }

}