<?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\UpdatesTransactionStatus;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Http\Resources\BillGroupResource;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class CancelBillGroupLogic extends AbstractControllerLogic
{

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

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

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

    /**
     * CancelBillGroupLogic constructor.
     * @param FetchesBillGroup $fetchesBillGroup
     * @param UpdatesTransactionStatus $updatesTransactionStatus
     */
    public function __construct(FetchesBillGroup $fetchesBillGroup, UpdatesTransactionStatus $updatesTransactionStatus)
    {
        $this->fetchesBillGroup = $fetchesBillGroup;
        $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) {
            if ($transaction->status === ApprovalStatus::APPROVED || $transaction->status === ApprovalStatus::COMPLETED) {
                $this->updatesTransactionStatus->execute($transaction, ApprovalStatus::PENDING_VERIFICATION);
            }
        }

        $billGroup->status = ApprovalStatus::PENDING_VERIFICATION;
        $billGroup->save();
        
        return $this->resourceResponse(new BillGroupResource($billGroup));
    }

}