<?php

namespace App\Services\Equipment;

use App\Entities\CommonEntity;
use App\Entities\Customer\ServiceEntity;
use App\Entities\Equipment\ServerEntity;
use App\Entities\Equipment\ServerPartEntity;
use App\Entities\Part\PartEntity;
use App\Forms\Equipment\ServerPartForm;
use App\Helpers\Equipment\ServerPartHelper;
use App\Models\Equipment\ServerPartModel;
use App\Services\Part\PartService;
use RuntimeException;

class ServerPartService extends EquipmentService
{
    protected string $formClass = ServerPartForm::class;
    protected string $helperClass = ServerPartHelper::class;

    public function __construct(ServerPartModel $model)
    {
        parent::__construct($model);
        $this->addClassPaths('ServerPart');
    }

    public function getEntityClass(): string
    {
        return ServerPartEntity::class;
    }

    private function getPartService(string $type): PartService
    {
        return service('part_' . strtolower($type) . 'service');
    }

    protected function getEntity_process(mixed $entity): ServerPartEntity
    {
        return $entity;
    }

    private function getBillingAtByServiceEntity(ServiceEntity $serviceEntity, string $billing): ?string
    {
        if ($billing === PAYMENT['BILLING']['MONTH']) {
            return $serviceEntity->getBillingAt();
        } elseif ($billing === PAYMENT['BILLING']['ONETIME']) {
            return date("Y-m-d");
        }
        return null;
    }

    private function setPartTitleByPartEntity(array $formDatas): string
    {
        $partEntity = $this->getPartService($formDatas['type'])->getEntity($formDatas['part_uid']);
        if (!$partEntity instanceof PartEntity) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: {$formDatas['part_uid']}에 해당하는 파트정보을 찾을수 없습니다.");
        }
        return $partEntity->getTitle();
    }

    private function getFormDatasForServerPart(array $formDatas, ServerEntity $serverEntity): array
    {
        if (empty($formDatas['serverinfo_uid'])) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: 서버번호가 지정되지 않았습니다.");
        }
        if (empty($formDatas['type'])) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: 부품형식이 지정되지 않았습니다.");
        }
        if (empty($formDatas['billing'])) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: 청구방법이 지정되지 않았습니다.");
        }
        if (empty($formDatas['part_uid'])) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: 파트번호가 지정되지 않았습니다.");
        }

        $formDatas['title'] = $this->setPartTitleByPartEntity($formDatas);

        // ✅ ServerPart는 serverinfo_uid 기준으로 움직인다.
        // serviceinfo_uid는 serverEntity의 "현재 상태"에서만 참고한다.
        $serviceEntity = null;
        if ($serverEntity->getServiceInfoUid()) {
            $serviceEntity = service('customer_serviceservice')->getEntity($serverEntity->getServiceInfoUid());
        }

        $formDatas['billing_at'] = null;
        if ($serviceEntity instanceof ServiceEntity) {
            $formDatas['billing_at'] = $this->getBillingAtByServiceEntity($serviceEntity, $formDatas['billing']);
        }

        $formDatas['clientinfo_uid'] = $serverEntity->getClientInfoUid();
        $formDatas['serviceinfo_uid'] = $serverEntity->getServiceInfoUid();

        return $formDatas;
    }

    //서비스 금액 재계산용
    private function recalcAmount(ServerPartEntity $entity): void
    {
        //월비용 서버파트 정보일 경우 서버금액 재계산
        if ($entity->getBilling() == PAYMENT['BILLING']['MONTH'] && $entity->getServerInfoUid()) {
            $serverEntity = service('equipment_serverservice')->getEntity($entity->getServerInfoUid());
            if ($serverEntity instanceof ServerEntity) {
                service('equipment_serverservice')->recalcAmount($serverEntity);
            }
        }
    }

    protected function create_process(array $formDatas): CommonEntity
    {
        $serverEntity = service('equipment_serverservice')->getEntity($formDatas['serverinfo_uid']);
        if (!$serverEntity instanceof ServerEntity) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: {$formDatas['serverinfo_uid']}에 해당하는 서버정보을 찾을수 없습니다.");
        }

        $formDatas = $this->getFormDatasForServerPart($formDatas, $serverEntity);

        $entity = parent::create_process($formDatas);
        if (!$entity instanceof ServerPartEntity) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: Return Type은 ServerPartEntity만 가능");
        }

        // dd($entity);
        $this->getPartService($entity->getType())->attachToServerPart($entity);

        // ✅ 서버가 서비스에 붙어 있을 때만 결제/동기화
        if ($entity->getServiceInfoUid()) {
            if ($entity->getBilling() == PAYMENT['BILLING']['MONTH']) {
                $this->recalcAmount($entity);
            }
            if ($entity->getBilling() == PAYMENT['BILLING']['ONETIME']) {
                service('paymentservice')->createByServerPart($entity);
            }
        }
        return $entity;
    }

    protected function modify_process($entity, array $formDatas): CommonEntity
    {
        $serverEntity = service('equipment_serverservice')->getEntity($formDatas['serverinfo_uid']);
        if (!$serverEntity instanceof ServerEntity) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: {$formDatas['serverinfo_uid']}에 해당하는 서버정보을 찾을수 없습니다.");
        }

        //기존정보 우선 저장
        $oldEntity = clone $entity;

        $entity = parent::modify_process($entity, $this->getFormDatasForServerPart($formDatas, $serverEntity));
        if (!$entity instanceof ServerPartEntity) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: Return Type은 ServerPartEntity만 가능");
        }
        $this->getPartService($entity->getType())->modifyServerPart($oldEntity, $entity);

        // ✅ 월별용 처리 (서버파트가 변경되었으므로 서버파트의 Billing이 MONTH이면 서비스/결제 동기화)
        if ($entity->getBilling() == PAYMENT['BILLING']['MONTH'] && $entity->getServerInfoUid()) {
            $this->recalcAmount($entity);
        }
        // ✅ 일회성용 처리
        if ($entity->getBilling() == PAYMENT['BILLING']['ONETIME']) {
            service('paymentservice')->modifyByServerPart($oldEntity, $entity);
        }
        return $entity;
    }

    protected function delete_process($entity): ServerPartEntity
    {
        if (!$entity instanceof ServerPartEntity) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: ServerPartEntity만 가능");
        }

        //기존정보 우선 저장
        $oldEntity = clone $entity;

        $this->getPartService($entity->getType())->detachFromServerPart($entity);

        $entity = parent::delete_process($entity);
        if (!$entity instanceof ServerPartEntity) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: Return Type은 ServerPartEntity만 가능");
        }
        // ✅서버파트가 삭제되었으므로 서버파트의 Billing이 MONTH이면 서비스/결제 동기화
        if ($oldEntity->getBilling() == PAYMENT['BILLING']['MONTH'] && $oldEntity->getServerInfoUid()) {
            $this->recalcAmount($oldEntity);
        }
        // ✅ ONETIME 미납 결제 삭제는 "보류" (여기서는 아무것도 안함)
        return $entity;
    }

    //서버추가시 기본파트 자동추가용
    public function attachToServer(ServerEntity $serverEntity): void
    {
        $chassisEntity = service("equipment_chassisservice")->getEntity($serverEntity->getChassisInfoUid());

        foreach (SERVERPART['SERVER_PARTTYPES'] as $parttype) {
            $uid_function = "get{$parttype}InfoUid";
            $cnt_function = "get{$parttype}Cnt";

            $uid = $chassisEntity->$uid_function();
            $cnt = $chassisEntity->$cnt_function();
            if ($uid === null)
                continue;

            $partEntity = $this->getPartService($parttype)->getEntity($uid);
            if (!$partEntity instanceof PartEntity) {
                throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: {$uid}에 해당하는 {$parttype} 파트정보를 찾을수 없습니다.");
            }

            $formDatas = [];
            $formDatas['serverinfo_uid'] = $serverEntity->getPK();
            $formDatas["part_uid"] = $partEntity->getPK();
            $formDatas['billing'] = PAYMENT['BILLING']['BASE'];
            $formDatas['type'] = $parttype;
            $formDatas['title'] = $partEntity->getTitle();
            $formDatas['amount'] = $partEntity->getPrice();
            $formDatas['cnt'] = $cnt;

            $this->create_process($formDatas);
        }
    }

    /**
     * ✅ 서버 해지/분리 시 서버파트 회수 처리
     */
    public function detachFromServer(ServerEntity $serverEntity): void
    {
        foreach ($this->getEntities(['serverinfo_uid' => $serverEntity->getPK(), "billing !=" => PAYMENT['BILLING']['BASE']]) as $entity) {
            if (!$entity instanceof ServerPartEntity) {
                continue;
            }
            //파트정보 해지
            $this->getPartService($entity->getType())->detachFromServerPart($entity);
            //서버파트 해지
            parent::delete_process($entity);
            //서비스금액 재계산
            if ($entity->getBilling() == PAYMENT['BILLING']['MONTH'] && $entity->getServerInfoUid()) {
                $this->recalcAmount($entity);
            }
        }
    }
}
