<?php
// +----------------------------------------------------------------------
// | onezan-admin 快速开发的管理平台
// +----------------------------------------------------------------------
// | 官方网址：https://www.onezan.cn
// +----------------------------------------------------------------------
// | onezan团队 版权所有 开源版本可自由商用
// +----------------------------------------------------------------------
// | Author: 543885307@qq.com
// +----------------------------------------------------------------------
namespace app\validate\domain;


/**
 * 地址领域验证器
 * @package app\validate\domain
 */
class AddressDomainValidator implements DomainValidatorInterface
{

    protected array $hooks = [];


    /**
     * 注册验证钩子
     * @param \app\validate\domain\hooks\ValidationHook $hook 钩子实例
     * @return void
     */
    public function registerHook(\app\validate\domain\hooks\ValidationHook $hook): void
    {
        $this->hooks[] = $hook;
    }


    /**
     * 校验地址数据
     * @param array $data
     * @param string $scene
     * @return array
     */
    public function validate(array $data, string $scene = ''): array
    {
        $errors = match ($scene) {
            'create' => $this->validateCreate($data),
            'update' => $this->validateUpdate($data),
            default => [],
        };

        foreach ($this->hooks as $hook) {
            $hookErrors = $hook->onAddressValidate($data, $scene);
            if (!empty($hookErrors)) {
                $errors = array_merge($errors, $hookErrors);
            }
        }

        return ['ok' => empty($errors), 'errors' => $errors];
    }

    /**
     * 校验创建地址数据
     * @param array $data
     * @return array 错误信息数组
     */
    private function validateCreate(array $data): array
    {
        $errors = [];
        $name = trim((string)($data['name'] ?? ''));
        if ($name === '') {
            $errors['name'] = 'NAME_REQUIRED';
        }
        $phone = trim((string)($data['phone'] ?? ''));
        if ($phone === '') {
            $errors['phone'] = 'PHONE_REQUIRED';
        }
        $detail = trim((string)($data['detail'] ?? ''));
        if ($detail === '') {
            $errors['detail'] = 'DETAIL_REQUIRED';
        }
        return $errors;
    }

    /**
     * 校验更新地址数据
     * @param array $data
     * @return array 错误信息数组
     */
    private function validateUpdate(array $data): array
    {
        $errors = [];
        if (empty($data['id'] ?? 0)) {
            $errors['id'] = 'ADDRESS_ID_REQUIRED';
        }
        $name = trim((string)($data['name'] ?? ''));
        if ($name === '') {
            $errors['name'] = 'NAME_REQUIRED';
        }
        $phone = trim((string)($data['phone'] ?? ''));
        if ($phone === '') {
            $errors['phone'] = 'PHONE_REQUIRED';
        }
        $detail = trim((string)($data['detail'] ?? ''));
        if ($detail === '') {
            $errors['detail'] = 'DETAIL_REQUIRED';
        }
        return $errors;
    }
}