<?php

namespace App\Services\Equipment\ServerPart;

use App\Entities\Equipment\PartEntity;
use App\Entities\Equipment\ServerPartEntity;
use App\Interfaces\Equipment\ServerPartInterface;
use App\Services\Equipment\PartService as ParentService;

class PartService extends ParentService implements ServerPartInterface
{
    private ?ServerPartEntity $_serverPartEntity = null;
    public function __construct()
    {
        parent::__construct();
    }

    public function setServerPartEntity(ServerPartEntity $entity): self
    {
        $this->_serverPartEntity = $entity;
        return $this;
    }
    public function getServerPartEntity(): ServerPartEntity
    {
        if (!$this->_serverPartEntity instanceof ServerPartEntity) {
            throw new \Exception(__METHOD__ . "에서 오류발생: 서버파트정보가 정의되지 않았습니다.");
        }
        return $this->_serverPartEntity;
    }
    //서버연결정보용 등록
    private function action_process(string $action): PartEntity
    {
        //부품정보가져오기
        $entity = $this->getEntity($this->getServerPartEntity()->getPartUID());
        if (!$entity instanceof PartEntity) {
            throw new \Exception("{$this->getServerPartEntity()->getPartUID()}에 해당하는 부품정보를 찾을수없습니다.");
        }
        //부품정보에 서버정보 설정 및 서비스,고객정보 정의
        $formDatas = [];
        if ($action === "return") { //해지된 부품 재고 반납 처리
            $formDatas['stock'] = $entity->getStock() + $this->getServerPartEntity()->getCnt();
        }
        if ($action === "use") { //사용된 부품 재고 사용처리
            if ($entity->getStock() < $this->getServerPartEntity()->getCnt()) {
                throw new \Exception("현재 재고수[{$entity->getStock()}]보다 지정하신 갯수({$this->getServerPartEntity()->getCnt()})가 더 많습니다.");
            }
            $formDatas['stock'] = $entity->getStock() - $this->getServerPartEntity()->getCnt();
        }
        return $this->modify($entity, $formDatas);
    }

    public function createServerPart(): ServerPartEntity
    {
        $entity = $this->action_process("use");
        return $this->getServerPartEntity()->setPartEntity($entity);
    }
    public function modifyServerPart(): ServerPartEntity
    {
        return $this->createServerPart();
    }
    public function deleteServerPart(): ServerPartEntity
    {
        $entity = $this->action_process("return");
        return $this->getServerPartEntity()->setPartEntity($entity);
    }
}
