<?php

namespace App\Services\Customer\Wallet;

use App\DTOs\Customer\Wallet\AccountDTO;
use App\Entities\CommonEntity;
use App\Entities\Customer\ClientEntity;
use App\Entities\Customer\Wallet\AccountEntity;
use App\Forms\Customer\Wallet\AccountForm;
use App\Helpers\Customer\Wallet\AccountHelper;
use App\Models\Customer\Wallet\AccountModel;
use RuntimeException;

class AccountService extends WalletService
{
    const CLIENTINFO_BALANCE_FIELD = 'account_balance';
    protected string $formClass = AccountForm::class;
    protected string $helperClass = AccountHelper::class;

    public function __construct(AccountModel $model)
    {
        parent::__construct($model);
        $this->addClassPaths('Account');
    }
    public function getDTOClass(): string
    {
        return AccountDTO::class;
    }
    public function createDTO(array $formDatas): AccountDTO
    {
        return new AccountDTO($formDatas);
    }
    public function getEntityClass(): string
    {
        return AccountEntity::class;
    }
    //기본 기능부분
    protected function getEntity_process(mixed $entity): AccountEntity
    {
        return $entity;
    }
    protected function modify_process($entity, array $formDatas): CommonEntity
    {
        throw new RuntimeException("예치금정보는 수정이 불가합니다.");
    }
    //List 검색용
    //FormFilter 조건절 처리
    //검색어조건절처리
    public function setSearchWord(string $word): void
    {
        $this->model->orLike($this->model->getTable() . '.alias', $word, 'both');
        parent::setSearchWord($word);
    }
    //입금,쿠폰 충전 처리
    protected function deposit_process(ClientEntity $clientEntity, array $formDatas): array
    {
        if (!array_key_exists('amount', $formDatas)) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: 출금액이 정의되지 않았습니다.");
        }
        //최종처리
        $formDatas['balance'] = $clientEntity->getAccountBalance() + $formDatas['amount'];
        if ($formDatas['balance'] < 0) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: 잔액이 0보다 값이 정의 되었습니다.");
        }
        //고객 잔액 갱신
        service('customer_clientservice')->modify($clientEntity->getPK(), [self::CLIENTINFO_BALANCE_FIELD => $formDatas['balance']]);
        return parent::deposit_process($clientEntity, $formDatas);
    }
    //결제 관련 출금 처리
    protected function withdrawal_process(ClientEntity $clientEntity, array $formDatas): array
    {
        try {
            if (!array_key_exists('amount', $formDatas)) {
                throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: 출금액이 정의되지 않았습니다.");
            }
            if ($clientEntity->getAccountBalance() < $formDatas['amount']) {
                throw new RuntimeException(sprintf(
                    "%s 에서 오류발생: 출금액(%s원) , %s 고객의 예치금액(%s원)이 부족합니다.",
                    static::class . '->' . __FUNCTION__,
                    number_format($formDatas['amount']),
                    $clientEntity->getTitle(),
                    number_format($clientEntity->getAccountBalance())
                ));
            }
            //최종처리
            $formDatas['bank'] = array_key_exists('bank', $formDatas) ? $formDatas['bank'] : BANKS['결제차감'];
            $formDatas['alias'] = array_key_exists('alias', $formDatas) ? $formDatas['alias'] : $clientEntity->getTitle();
            $formDatas['balance'] = $clientEntity->getAccountBalance() - $formDatas['amount'];
            if ($formDatas['balance'] < 0) {
                throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: 잔액({$formDatas['balance']})이 0보다 작은 값이 정의되었습니다.");
            }
            //고객의 Account Balance수정
            service('customer_clientservice')->modify($clientEntity->getPK(), [self::CLIENTINFO_BALANCE_FIELD => $formDatas['balance']]);
            return parent::withdrawal_process($clientEntity, $formDatas);
        } catch (\Throwable $e) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생:" . $e->getMessage());
        }
    }
}
