<?php

namespace App\Services\Customer;

use App\Entities\CommonEntity;
use App\Entities\Customer\ServiceEntity;
use App\Forms\CommonForm;
use App\Forms\Customer\ServiceForm;
use App\Helpers\Customer\ServiceHelper;
use App\Models\Customer\ServiceModel;
use DateTimeImmutable;
use DateTimeZone;
use RuntimeException;

class ServiceService extends CustomerService
{
    protected string $formClass = ServiceForm::class;
    protected string $helperClass = ServiceHelper::class;

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

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

    final public function getNewServiceEntities(int $interval, string $status = STATUS['AVAILABLE']): array
    {
        return $this->getEntities(["start_at >= NOW()-INTERVAL {$interval} DAY" => null, "status" => $status]);
    }

    final public function getTotalAmounts($where = []): array
    {
        $rows = $this->model->groupBy('clientinfo_uid')->select("clientinfo_uid,SUM(amount) AS amount")
            ->where($where)
            ->get()->getResult();

        $amounts = [];
        foreach ($rows as $row) {
            $amounts[$row->clientinfo_uid] = $row->amount;
        }
        return $amounts;
    }

    final public function getNextMonthDate(ServiceEntity $entity): string
    {
        $date = new DateTimeImmutable($entity->getBillingAt(), new DateTimeZone('Asia/Tokyo'));
        $day = (int) $date->format('d');

        $date = $date->modify('first day of next month');
        $lastDayOfNextMonth = (int) $date->format('t');

        if ($day > $lastDayOfNextMonth) {
            $day = $lastDayOfNextMonth;
        }

        $date = $date->setDate((int) $date->format('Y'), (int) $date->format('m'), $day);
        return $date->format('Y-m-d');
    }

    final public function updateBillingAt(int $uid, string $billing_at): CommonEntity
    {
        $entity = $this->getEntity($uid);
        if (!$entity instanceof ServiceEntity) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생:{$uid}에 해당하는 서비스정보를 찾을 수 업습니다.");
        }
        $formDatas = ['billing_at' => $billing_at];
        return parent::modify_process($entity, $formDatas);
    }

    //서비스 관련 총 금액
    private function getCalculatedAmount(ServiceEntity $entity): int
    {
        //서버 관련 금액
        $server_amount = service('equipment_serverservice')->getCalculatedAmount($entity->getServerInfoUid());
        return (int) $server_amount + (int) $entity->getRack() + (int) $entity->getLine() - $entity->getSale();
    }

    //서비스 금액 설정
    final public function recalcAmount(ServiceEntity $entity): ServiceEntity
    {
        $formDatas = ['amount' => $this->getCalculatedAmount($entity)];
        $entity = parent::modify_process($entity, $formDatas);
        if (!$entity instanceof ServiceEntity) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생:Return Type은 ServiceEntity만 가능");
        }
        return $entity;
    }

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

    protected function create_process(array $formDatas): ServiceEntity
    {
        if (!array_key_exists('site', $formDatas) || empty($formDatas['site'])) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: 사이트가 지정되지 않았습니다.");
        }
        if (!array_key_exists('serverinfo_uid', $formDatas) || empty($formDatas['serverinfo_uid'])) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: 서버가 지정되지 않았습니다.");
        }

        $formDatas['code'] = $formDatas['site'] . "_s" . uniqid();
        $formDatas['amount'] = 0;
        $entity = parent::create_process($formDatas);
        if (!$entity instanceof ServiceEntity) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생:Return Type은 ServiceEntity만 가능");
        }
        //서버 설정
        service('equipment_serverservice')->attatchToService($entity, $entity->getServerInfoUid());
        //서비스 금액 설정
        $entity = $this->recalcAmount($entity);
        //결제 추가
        service('paymentservice')->createByService($entity);
        return $entity;
    }

    protected function modify_process_validate(CommonForm &$actionForm, array $formDatas)
    {
        $actionForm->validate($formDatas, true);  // ✅ 여기서 검증
    }
    protected function modify_process($entity, array $formDatas): ServiceEntity
    {
        if (empty($formDatas['serverinfo_uid'])) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: 서버가 지정되지 않았습니다.");
        }
        //기존 정보 저장
        $oldEntity = clone $entity;

        $entity = parent::modify_process($entity, $formDatas);
        if (!$entity instanceof ServiceEntity) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생:Return Type은 ServiceEntity만 가능");
        }
        //서버 설정
        if ($oldEntity->getServerInfoUid() !== $entity->getServerInfoUid()) {
            service('equipment_serverservice')->modifyByService($oldEntity, $entity);
        }
        //서비스 금액 설정
        $entity = $this->recalcAmount($entity);
        //결제비 설정
        service('paymentservice')->modifyByService($oldEntity, $entity);
        return $entity;
    }

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

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

        $entity = parent::delete_process($entity);
        if (!$entity instanceof ServiceEntity) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생:Return Type은 ServiceEntity만 가능");
        }
        if ($oldEntity->getServerInfoUid()) {
            service('equipment_serverservice')->deatchFromService($oldEntity->getServerInfoUid());
        }
        return $oldEntity;
    }

    public function history(string|int $uid, string $history): CommonEntity
    {
        return $this->dbTransaction(function () use ($uid, $history) {
            $entity = $this->getEntity($uid);
            if (!$entity) {
                throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: {$uid}에 해당하는 정보을 찾을수 없습니다.");
            }
            $formDatas['user_uid'] = (int) $this->getAuthContext()->getUID();
            $formDatas['history'] = $history;
            // 검증 통과 후 엔티티 반영
            $entity->fill($formDatas);
            if (!$entity->hasChanged()) {
                return $entity;
            }
            return $this->save_process($entity);
        }, __FUNCTION__);
    }
}
