<?php

namespace App\Classes\Modules\Transactions\ControllersLogic;

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

class DeleteGroupLogic extends AbstractControllerLogic
{

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

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

    /** @var FetchesGroup */
    private $fetchesGroup;

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

    /**
     * DeleteGroupLogic constructor.
     * @param updatesTransactionStatus $updatesTransactionStatus
     * @param FetchesGroup $fetchesGroup
     * @param DeletesTransaction $deletesTransaction
     */
    public function __construct(updatesTransactionStatus $updatesTransactionStatus, FetchesGroup $fetchesGroup, DeletesTransaction $deletesTransaction)
    {
        $this->updatesTransactionStatus = $updatesTransactionStatus;
        $this->fetchesGroup = $fetchesGroup;
        $this->deletesTransaction = $deletesTransaction;
    }

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

        $items = $group->transactions()->get();

        foreach($items as $item) {
            $bill = $item;
            $payment = $bill->owner;
            $group->transactions()->detach($bill->id);
            $this->updatesTransactionStatus->execute($payment, ApprovalStatus::APPROVED);
            $this->deletesTransaction->execute($bill);
        }

        $group->delete();
        
        return $this->resourceResponse(new GroupResource($group));
    }

}