<?php

namespace App\Services\Equipment;

use App\Entities\Customer\ServiceEntity;
use App\Entities\Equipment\ServerEntity;
use App\Forms\Equipment\ServerForm;
use App\Helpers\Equipment\ServerHelper;
use App\Models\Equipment\ServerModel;
use RuntimeException;

class ServerService extends EquipmentService
{
    protected string $formClass = ServerForm::class;
    protected string $helperClass = ServerHelper::class;

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

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

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


    final public function getTotalServiceCount(array $where = []): array
    {
        $totalCounts = [
            'chiba_summary' => 0,
            'tokyo_summary' => 0,
            'all_summary' => 0,
            'normal' => ['chiba' => 0, 'tokyo' => 0, 'summary' => 0],
            'defence' => ['chiba' => 0, 'tokyo' => 0, 'summary' => 0],
            'dedicated' => ['chiba' => 0, 'tokyo' => 0, 'summary' => 0],
            'alternative' => ['chiba' => 0, 'tokyo' => 0, 'summary' => 0],
            'vpn' => ['chiba' => 0, 'tokyo' => 0, 'summary' => 0],
            'event' => ['chiba' => 0, 'tokyo' => 0, 'summary' => 0],
            'test' => ['chiba' => 0, 'tokyo' => 0, 'summary' => 0],
        ];
        $builder = $this->model->select("serverinfo.type, COUNT(CASE WHEN serviceinfo.location = 'chiba' THEN 1 END) AS chiba, COUNT(CASE WHEN serviceinfo.location = 'tokyo' THEN 1 END) AS tokyo, COUNT(CASE WHEN serviceinfo.location IN ('chiba', 'tokyo') THEN 1 END) AS summary")
            ->join('serviceinfo', 'serviceinfo.uid = serverinfo.serviceinfo_uid')
            ->where($where)
            ->groupBy('serverinfo.type')
            ->builder();
        // echo $builder->getCompiledSelect(false) . "<BR>";
        //초기화 없이 SQL만 보고 싶을 때: getCompiledSelect(false) ← 꼭 false!
        // dd($rows);
        foreach ($builder->get()->getResult() as $row) {
            $totalCounts[$row->type]['chiba'] = $row->chiba;
            $totalCounts[$row->type]['tokyo'] = $row->tokyo;
            $totalCounts[$row->type]['summary'] += $row->summary;
            $totalCounts['chiba_summary'] += $row->chiba;
            $totalCounts['tokyo_summary'] += $row->tokyo;
            $totalCounts['all_summary'] = $totalCounts['chiba_summary'] + $totalCounts['tokyo_summary'];
        }
        // dd($totalCounts);
        return $totalCounts;
    }
    //전체 검색어에 따른 서버정보를 검색 후 해당하는 서비스리스트를 가져온다.
    final public function getSearchServices(string $keyword): array
    {
        $keyword = trim($keyword);
        $builder = $this->model->distinct()->select('serverinfo.serviceinfo_uid AS serviceinfo_uid')
            ->join('clientinfo', 'clientinfo.uid = serverinfo.clientinfo_uid')
            ->join('serverpartinfo', 'serverpartinfo.serverinfo_uid = serverinfo.uid')
            ->groupStart()
            ->like('clientinfo.name', $keyword, 'both', null, true) // escape=true
            ->orLike('serverinfo.code', $keyword, 'both', null, true)
            ->orLike('serverinfo.ip', $keyword, 'both', null, true)
            ->orLike('serverinfo.title', $keyword, 'both', null, true)
            ->orLike('serverpartinfo.title', $keyword, 'both', null, true)
            ->groupEnd()
            ->builder();
        // echo $builder->getCompiledSelect(false); //초기화 없이 SQL만 보고 싶을 때: getCompiledSelect(false) ← 꼭 false!
        $rows = $builder->get()->getResult();
        if (!count($rows)) {
            return [];
        }
        return $rows;
    }
    //서버 Title별 카운트수
    final public function getStockCount(): array
    {
        $builder = $this->model->select('title,COUNT(*) AS cnt')->groupBy('title')->builder();
        // echo $builder->getCompiledSelect(false); //초기화 없이 SQL만 보고 싶을 때: getCompiledSelect(false) ← 꼭 false!
        // dd($builder->get()->getResult());
        $rows = [];
        foreach ($builder->get()->getResult() as $row) {
            $rows[$row->title] = $row->cnt;
        }
        return $rows;
    }

    //총서버금액
    final public function getCalculatedAmount(int $uid): int
    {
        $entity = $this->getEntity($uid);
        if (!$entity instanceof ServerEntity) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: {$uid} 서버 정보를 찾을수 없습니다.");
        }
        $caculatedAmount = $entity->getPrice();
        foreach (service('equipment_serverpartservice')->getEntities(['serverinfo_uid' => $entity->getPK(), 'billing' => PAYMENT['BILLING']['MONTH']]) as $serverPartEntity) {
            log_message('debug', $serverPartEntity->getCustomTitle() . '::' . $serverPartEntity->getCalculatedAmount());
            $caculatedAmount += $serverPartEntity->getCalculatedAmount();
        }
        return $caculatedAmount;
    }

    public function recalcAmount(ServerEntity $entity): void
    {
        if ($entity->getServiceInfoUid()) {
            $serviceEntity = service('customer_serviceservice')->getEntity($entity->getServiceInfoUid());
            if (!$serviceEntity instanceof ServiceEntity) {
                throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: {$entity->getServiceInfoUid()} 서비스정보를 찾을수 없습니다.");
            }
            // ✅ 핵심 추가: 서비스금액 변경 및 payment Sync용
            if ($serviceEntity->getServerInfoUid() === $entity->getServiceInfoUid()) {
                $oldServiceEntity = clone $serviceEntity;
                $serviceEntity = service('customer_serviceservice')->recalcAmount($serviceEntity);
                //결제비 설정
                service('paymentservice')->modifyByService($oldServiceEntity, $serviceEntity);
            }
        }
    }

    protected function create_process(array $formDatas): ServerEntity
    {
        $entity = parent::create_process($formDatas);
        if (!$entity instanceof ServerEntity) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생:Return Type은 ServerEntity만 가능");
        }
        if ($entity->getIP()) {
            service('part_ipservice')->attachToServer($entity);
        }
        if ($entity->getSwitchInfoUid()) {
            service('part_switchservice')->attachToServer($entity);
        }
        service('equipment_chassisservice')->attachToServer($entity);
        service('equipment_serverpartservice')->attachToServer($entity);
        return $entity;
    }

    protected function modify_process($entity, array $formDatas): ServerEntity
    {
        if (!array_key_exists('chassisinfo_uid', $formDatas)) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . '에서 오류발생: 샷시정보가 정의되지 않았습니다.');
        }

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

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

        if ($oldEntity->getIP() !== $entity->getIP()) {
            if ($oldEntity->getIP()) {
                service('part_ipservice')->detachFromServer($oldEntity);
            }
            if ($entity->getIP()) {
                service('part_ipservice')->attachToServer($entity);
            }
        }

        if ($oldEntity->getSwitchInfoUid() !== $entity->getSwitchInfoUid()) {
            if (is_int($oldEntity->getSwitchInfoUid())) { //null이거나 공백인경우
                service('part_switchservice')->detachFromServer($oldEntity);
            }
            if ($entity->getSwitchInfoUid() !== null) {
                service('part_switchservice')->attachToServer($entity);
            }
        }

        if ($oldEntity->getChassisInfoUid() !== $entity->getChassisInfoUid()) {
            service('equipment_chassisservice')->detachFromServer($oldEntity);
            if ($entity->getChassisInfoUid() !== null) {
                service('equipment_chassisservice')->attachToServer($entity);
            }
        }
        //가격 변동이 있는 경우
        if ($oldEntity->getPrice() !== $entity->getPrice()) {
            $this->recalcAmount($entity);
        }
        return $entity;
    }

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

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

        //서버정보
        $entity = parent::delete_process($entity);
        if (!$entity instanceof ServerEntity) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생:Return Type은 ServiceEntity만 가능");
        }

        //서비스연결이 유지된 상태인경우
        if ($entity->getServiceInfoUid() !== null) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생:{$entity->getTitle()} 서버는 아직 서비스와 연결된 상태입니다.");
        }
        //IP정보
        if ($oldEntity->getIP()) {
            service('part_ipservice')->detachFromServer($oldEntity);
        }
        //Switch정보
        if ($oldEntity->getSwitchInfoUid()) {
            if (is_int($oldEntity->getSwitchInfoUid())) { //null이거나 공백인경우
                service('part_switchservice')->detachFromServer($oldEntity);
            }
        }
        //샷시정보
        if ($oldEntity->getChassisInfoUid()) {
            service('equipment_chassisservice')->detachFromServer($oldEntity);
        }
        //파트정보
        service('equipment_serverpartservice')->detachFromServer($oldEntity);
        return $oldEntity;
    }

    public function setSearchWord(string $word): void
    {
        $this->model->orLike($this->model->getTable() . '.ip', $word, 'both');
        $this->model->orLike($this->model->getTable() . '.ilo_ip', $word, 'both');
        parent::setSearchWord($word);
    }

    public function attatchToService(ServiceEntity $serviceEntity, $uid, array $formDatas = []): void
    {
        $entity = $this->getEntity($uid);
        if (!$entity instanceof ServerEntity) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: {$uid}에 해당하는 서버정보을 찾을수 없습니다.");
        }
        $formDatas['serviceinfo_uid'] = $serviceEntity->getPK();
        $formDatas["clientinfo_uid"] = $serviceEntity->getClientInfoUid();
        $formDatas['status'] = $formDatas['status'] ?? STATUS['OCCUPIED'];
        parent::modify_process($entity, $formDatas);
    }

    //해지처리 (중요: server.serviceinfo_uid == null 이후에 ServerPart detach 호출)
    public function deatchFromService($uid, array $formDatas = []): void
    {
        $entity = $this->getEntity($uid);
        if (!$entity instanceof ServerEntity) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: {$uid}에 해당하는 서버정보을 찾을수 없습니다.");
        }

        // ✅ 분리 전 서비스 스냅샷
        $oldServiceEntity = null;
        $serviceUid = $entity->getServiceInfoUid();
        if ($serviceUid) {
            $svc = service('customer_serviceservice')->getEntity($serviceUid);
            if ($svc instanceof ServiceEntity) {
                $oldServiceEntity = clone $svc;
            }
        }

        // 파트 detach(네트워크 자원)
        if ($entity->getIP()) {
            service('part_ipservice')->detachFromServer($entity);
        }
        if ($entity->getSwitchInfoUid()) {
            service('part_switchservice')->detachFromServer($entity);
        }

        // ✅ 먼저 서버를 서비스에서 분리 (serviceinfo_uid=null)
        $formDatas['serviceinfo_uid'] = null;
        $formDatas["clientinfo_uid"] = null;
        $formDatas["switchinfo_uid"] = null;
        $formDatas["ip"] = null;
        $formDatas['status'] = $formDatas['status'] ?? STATUS['AVAILABLE'];

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

        // ✅ 이제 server.serviceinfo_uid == null 상태이므로 정책 발동:
        // - MONTH 파트 삭제
        // - 월 미납 payment는 삭제/0원수정 금지, status=TERMINATED
        // - ONETIME 미납 삭제는 보류
        service('equipment_serverpartservice')->detachFromServer($entity, $oldServiceEntity);
    }

    // Service 메인서버 교체 시 서버 정합성 유지용
    public function modifyByService(ServiceEntity $oldServiceEntity, ServiceEntity $serviceEntity): void
    {
        // 기존 메인서버
        $oldServer = $this->getEntity($oldServiceEntity->getServerInfoUid());
        if (!$oldServer instanceof ServerEntity) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ .
                "에서 오류발생: {$oldServiceEntity->getServerInfoUid()} 기존 메인 서버정보를 찾을수 없습니다.");
        }

        // 신규 메인서버
        $newServerEntity = $this->getEntity($serviceEntity->getServerInfoUid());
        if (!$newServerEntity instanceof ServerEntity) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ .
                "에서 오류발생: {$serviceEntity->getServerInfoUid()} 신규 메인 서버정보를 찾을수 없습니다.");
        }

        // 신규 서버를 서비스에 붙임(occupied 처리 + client/service uid 세팅)
        // type은 기존 메인서버의 type을 승계 (normal/dedicated/defence 등)
        $this->attatchToService($serviceEntity, $newServerEntity->getPK(), [
            'type' => $oldServer->getType()
        ]);

        // 기존 메인서버는 대체 서버로 변경(서비스에 남겨둘지/분리할지는 정책에 따라 다름)
        // 여기서는 기존 동작 유지: alternative로만 바꿈
        parent::modify_process($oldServer, ['type' => 'alternative']);
    }
}
