<?php

namespace App\Services\Customer\Wallet;

use App\DTOs\Customer\Wallet\PointDTO;
use App\Entities\CommonEntity;
use App\Entities\Customer\ClientEntity;
use App\Entities\Customer\Wallet\PointEntity;
use App\Forms\Customer\Wallet\PointForm;
use App\Helpers\Customer\Wallet\PointHelper;
use App\Models\Customer\Wallet\PointModel;
use RuntimeException;

class PointService extends WalletService
{
    const CLIENTINFO_BALANCE_FIELD = 'point_balance';
    protected string $formClass = PointForm::class;
    protected string $helperClass = PointHelper::class;

    public function __construct(PointModel $model)
    {
        parent::__construct($model);
        $this->addClassPaths('Point');
    }
    public function getDTOClass(): string
    {
        return PointDTO::class;
    }
    public function createDTO(array $formDatas): PointDTO
    {
        return new PointDTO($formDatas);
    }
    public function getEntityClass(): string
    {
        return PointEntity::class;
    }
    //기본 기능부분
    protected function getEntity_process(mixed $entity): PointEntity
    {
        return $entity;
    }
    protected function modify_process($entity, array $formDatas): CommonEntity
    {
        throw new RuntimeException("포인트정보는 수정이 불가합니다.");
    }
    //List 검색용
    //FormFilter 조건절 처리
    //검색어조건절처리

    //결제 관련 포인트 사용 처리
    protected function withdrawal_process(ClientEntity $clientEntity, array $formDatas): array
    {
        if (!array_key_exists('amount', $formDatas)) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: 사용포인트가 정의되지 않았습니다.");
        }
        if ($clientEntity->getPointBalance() < $formDatas['amount']) {
            throw new RuntimeException(sprintf(
                "%s 에서 오류발생: 사용포인트(%s) , %s 잔여포인트(%s)가 부족합니다.",
                static::class . '->' . __FUNCTION__,
                number_format($formDatas['amount']),
                $clientEntity->getTitle(),
                number_format($clientEntity->getPointBalance())
            ));
        }
        //최종처리
        $formDatas['balance'] = $clientEntity->getPointBalance() - $formDatas['amount'];
        if ($formDatas['balance'] < 0) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: 잔여포인트({$formDatas['balance']})가 0보다 작은 값이 정의되었습니다.");
        }
        //고객 잔여포인트 갱신
        service('customer_clientservice')->modify_process($clientEntity, [self::CLIENTINFO_BALANCE_FIELD => $formDatas['balance']]);
        return parent::withdrawal_process($clientEntity, $formDatas);
    }
}
