<?php

namespace App\Classes\Modules\ControllersLogic\Companies;


use App\Classes\Modules\AddressBook\DataTransferObjects\AddressBookObject;
use App\Classes\Modules\AddressBook\Services\CreatesAddress;
use App\Classes\Modules\Companies\DataTransferObjects\CompanyObject;
use App\Classes\Modules\Companies\Services\CreatesCompany;
use App\Classes\Modules\ControllerLogic\Exceptions\InternalServerErrorException;
use App\Classes\Modules\ControllerLogic\Exceptions\ResourceConflictException;
use App\Classes\ValueObjects\Constants\HttpStatus;
use App\Models\Company;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class CreateCompanyLogic
{

    /** @var Company */
    private $repository;

    /** @var CreatesCompany */
    private $createsCompany;

    /** @var CreatesAddress */
    private $createsAddress;

    /**
     * CreateCompanyLogic constructor.
     * @param Company $repository
     * @param CreatesCompany $createsCompany
     * @param CreatesAddress $createsAddress
     */
    public function __construct(Company $repository, CreatesCompany $createsCompany, CreatesAddress $createsAddress)
    {
        $this->repository = $repository;
        $this->createsCompany = $createsCompany;
        $this->createsAddress = $createsAddress;
    }


    /**
     * @param Request $request
     * @return JsonResponse
     * @throws InternalServerErrorException
     */
    public function execute(Request $request){

        try {

            $object = new CompanyObject($request->input('marking'), $request->input('name'),$request->input('email'),
                $request->input('registration_no'), $request->input('tax_no'));
            $existing = $this->repository->where('marking', $object->getMarking())->get();

            if ($existing->count() !== 0) {
                throw new ResourceConflictException("Marking already exists");
            }

            $company = $this->createsCompany->execute($object);

            $address = new AddressBookObject(1, $company->id, $request->input('name'), $request->input('contact'),
                $request->input('street_one'), $request->input('street_two'), $request->input('city'),
                $request->input('state'), $request->input('post_code'), $request->input('country'), true, true);

            $this->createsAddress->execute($address);

            return new JsonResponse(null, HttpStatus::RESOURCE_CREATED);

        } catch (ResourceConflictException $exception){
            throw new InternalServerErrorException("Failed to create importer because {$exception->getMessage()}");
        }

    }


}