<?php
declare (strict_types=1);

namespace app\adminapi\service\message;

use app\common\model\sms\SmsConfig;
use app\common\service\sms\EasySmsConfig;
use app\common\service\sms\SmsConfigMapping;
use app\common\model\sms\SmsTemplate;
use Overtrue\EasySms\EasySms;
use core\base\BaseService;
use think\facade\Db;

class SmsConfigService extends BaseService
{
    public function __construct()
    {
        parent::__construct();
        $this->model = new SmsConfig();
    }

    public function getList(): array
    {
        return $this->model->order('id', 'desc')->select()->toArray();
    }

    public function getConfig(string $gateway): array
    {
        $row = $this->model->where('gateway', $gateway)->find();
        if (!$row) {
            return [];
        }

        $data = $row->toArray();
        $data['config_data'] = EasySmsConfig::decryptSensitiveData($gateway, $row['config_data']);
        return $data;
    }

    public function saveConfig(string $gateway, array $configData, ?int $id = null): bool
    {
        if (!EasySmsConfig::isGatewaySupported($gateway)) {
            self::setError('不支持的短信网关');
            return false;
        }

        $requiredFields = EasySmsConfig::getRequiredFields($gateway);
        foreach ($requiredFields as $field) {
            if (!isset($configData[$field]) || $configData[$field] === '') {
                self::setError("缺少必填参数: {$field}");
                return false;
            }
        }

        $configData = EasySmsConfig::encryptSensitiveData($gateway, $configData);
        $gatewayName = SmsConfigMapping::GATEWAY_NAMES[$gateway] ?? $gateway;

        $row = $id ? $this->model->where('id', $id)->find() : $this->model->where('gateway', $gateway)->find();
        $payload = [
            'gateway' => $gateway,
            'gateway_name' => $gatewayName,
            'config_data' => $configData,
        ];

        if ($row) {
            if ($id === null) {
                self::setError('已新增网关配置，请勿重复添加');
                return false;
            }
            if ($row['gateway'] !== $gateway && $this->model->where('gateway', $gateway)->find()) {
                self::setError('已新增网关配置，请勿重复添加');
                return false;
            }
            return (bool)$row->save($payload);
        }

        $payload['status'] = 0;
        return (bool)$this->model->save($payload);
    }

    public function switchGateway(string $gateway): bool
    {
        $row = $this->model->where('gateway', $gateway)->find();
        if (!$row) {
            self::setError('网关配置不存在');
            return false;
        }

        Db::startTrans();
        try {
            $this->model->where('status', 1)->update(['status' => 0]);
            $row->save(['status' => 1]);
            Db::commit();
        } catch (\Throwable $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }

        return true;
    }

    public function testConnection(string $gateway, string $testMobile): array
    {
        $row = $this->model->where('gateway', $gateway)->find();
        if (!$row) {
            return ['success' => false, 'message' => '网关配置不存在'];
        }

        try {
            $template = SmsTemplate::order('id', 'desc')->find();
            if (!$template) {
                return ['success' => false, 'message' => '请先配置短信模板'];
            }

            $config = EasySmsConfig::buildGatewayConfig($gateway, $row['config_data']);
            $easySms = new EasySms($config);

            $message = [
                'template' => $template['template_value'],
                'data' => ['code' => '123456'],
            ];

            $easySms->send($testMobile, $message);
            return ['success' => true, 'message' => '发送成功'];
        } catch (\Throwable $e) {
            return ['success' => false, 'message' => $e->getMessage()];
        }
    }

    public function deleteConfig(string $gateway = '', ?int $id = null): bool
    {
        if ($gateway === '' && ($id === null || $id <= 0)) {
            $this->setError('网关参数不能为空');
            return false;
        }

        Db::startTrans();
        try {
            $row = $id ? $this->model->where('id', $id)->find() : $this->model->where('gateway', $gateway)->find();
            if (!$row) {
                Db::rollback();
                $this->setError('网关配置不存在');
                return false;
            }

            $result = $row->delete();

            if (!$result) {
                Db::rollback();
                $this->setError('删除短信配置失败');
                return false;
            }
            Db::commit();
            return true;
        } catch (\Throwable $e) {
            Db::rollback();
            $this->setError($e->getMessage());
            return false;
        }
    }
}