<?php

namespace App\Services\Customer;

use App\Entities\Customer\ServiceItemEntity;
use App\Entities\Equipment\Part\IpEntity;
use App\Models\Customer\ServiceItemModel;
use App\Services\Customer\CustomerService;
use App\Services\Equipment\Part\IpService;

class ServiceItemService extends CustomerService
{
    private ?IpService $_ipService = null;
    public function __construct()
    {
        parent::__construct();
        $this->addClassName('ServiceItem');
    }
    public function getModelClass(): ServiceItemModel
    {
        return new ServiceItemModel();
    }
    public function getEntityClass(): ServiceItemEntity
    {
        return new ServiceItemEntity();
    }
    public function getIpService(): IpService
    {
        if (!$this->_ipService) {
            $this->_ipService = new IpService();
        }
        return $this->_ipService;
    }
    public function getFormFields(): array
    {
        return [
            "serviceinfo_uid",
            "item_type",
            "item_uid",
            "billing_cycle",
            "price",
            "amount",
            "start_at",
            "status",
        ];
    }
    public function getFilterFields(): array
    {
        return ["serviceinfo_uid", 'item_type', 'item_uid', 'billing_cycle', 'status'];
    }
    public function getBatchJobFields(): array
    {
        return ['status'];
    }
    public function getIndexFields(): array
    {
        return ['serviceinfo_uid', 'item_type', 'item_uid', 'billing_cycle', 'price', 'amount', 'start_at', 'updated_at', 'status'];
    }
    //Entity의 관련객체정의용
    //FieldForm관련용
    public function modify(mixed $entity, array $formDatas): ServiceItemEntity
    {
        //IP가 기존과 다를경우 //toggle,batchjob의 경우 $formDatas에 code가 없을수도 있음
        if (array_key_exists('item_type', $formDatas) && $formDatas['item_type'] !== 'IP') {
            //기존 IP의 경우 반환처리
            $this->getIpService()->setStatus($entity->getItemUID(), IpEntity::STATUS_AVAILABLE);
            //신규 설정된 IP의 경우 서비스중 변경처리
            $this->getIpService()->setStatus($formDatas['item_uid'], IpEntity::STATUS_OCCUPIED);
        }
        return parent::modify($entity, $formDatas);
    }
    public function delete(mixed $entity): ServiceItemEntity
    {
        //기존 Ip의 경우 반환처리
        if ($entity->getItemType() === 'IP') {
            $this->getIpService()->setStatus($entity->getItemUID(), IpEntity::STATUS_AVAILABLE);
        }
        return parent::delete($entity);
    }
}
