<?php

namespace App\Classes\Modules\Companies\ControllersLogic;


use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Companies\Services\FetchesCompany;
use App\Classes\Modules\Companies\Standards\Rules\CanFetchCompany;
use App\Http\Resources\EInvoiceInfoResource;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class FetchCompanyEInvoiceInfoLogic extends AbstractControllerLogic
{

    /**
     * @return array
     */
    protected function notification():array {
        return [
            'title' => 'Retrieved Company E-Invoice Info',
            'message' => 'You have successfully retrieved a Company E-Invoice Info'
        ];
    }

    /** @var CanFetchCompany */
    private $canFetchCompany;

    /** @var FetchesCompany */
    private $fetchesCompany;

    /**
     * FetchCompanyEInvoiceInfoLogic constructor.
     * @param CanFetchCompany $canFetchCompany
     * @param FetchesCompany $fetchesCompany
     */
    public function __construct(CanFetchCompany $canFetchCompany, FetchesCompany $fetchesCompany)
    {
        $this->canFetchCompany = $canFetchCompany;
        $this->fetchesCompany = $fetchesCompany;
    }


    /**
     * @param Request $request
     * @return JsonResponse
     * @throws \App\Classes\Exceptions\AccessForbiddenException
     * @throws \App\Classes\Exceptions\RequestValidationException
     */
    public function logic(Request $request) : JsonResponse
    {
        $this->canFetchCompany->passes();

        $company = $this->fetchesCompany->execute(['id' => $request->route('id')]);
        $eInvoiceInfo = $company->addresses()->where('billing', '=', false)->where('e_invoice', '=', true)->latest()->first();

        if($eInvoiceInfo){
            $eInvoiceInfo->tin = $company->tin;
            $eInvoiceInfo->msic_code = $company->msic_code;
            $eInvoiceInfo->e_invoice = $company->e_invoice;
            $eInvoiceInfo->e_invoice_requested_at = $company->e_invoice_requested_at;
        }
        else{
            return $this->response([]);
        }

        return $this->resourceResponse(new EInvoiceInfoResource($eInvoiceInfo));
    }
}
