<?php

namespace App\Processors\Customer\Service;

use App\Processor\ServiceInterface;
use App\Processors\Customer\ServiceContext;
use App\Processors\Customer\ServiceProcessor;
use App\Services\Customer\ServiceService;
use App\Services\Equipment\ServerService;
use App\Services\PaymentService;
use CodeIgniter\Database\BaseConnection;

class CreateProcessor extends ServiceProcessor implements ServiceInterface
{
  public function __construct(
    BaseConnection $db,
    ServiceService $serviceService,
    ServerService  $serverService,
    PaymentService $paymentService,
  ) {
    parent::__construct($db, $serviceService, $serverService, $paymentService);
  }

  public function process(ServiceContext $ctx): ServiceContext
  {
    if (!isset($ctx->formDatas['serverinfo_uid'])) {
      throw new \Exception('서버가 지정되지 않았습니다.');
    }
    // 1) 서비스 생성
    $entity = $this->serviceService->getModel()->create($ctx->formDatas);
    // 2) 서버 연결
    $serverEntity = $this->attachServer($entity);
    // 3) 금액 계산
    $amount = $this->serviceService->getCalculatedAmount($entity);
    $entity = $this->serviceService->getModel()->modify($entity, ['amount' => $amount]);
    // 4) 결제 생성
    $paymentEntity = $this->createPayment($entity, $serverEntity);
    // 5) 서비스 링크 갱신(FK 반영)
    $entity = $this->serviceService->getModel()->modify($entity, [
      'serverinfo_id' => $serverEntity->getPK(),
      'payment_uid'   => $paymentEntity->getPK(),
    ]);
    // 6) 로그 (필요 시 이벤트로 대체)
    $this->setLog($entity);
    $this->db->transComplete();
    if ($this->db->transStatus() === false) {
      throw new \Exception('트랜잭션 실패');
    }
    return $entity;
  }
}
