<?php
declare (strict_types=1);

namespace app\adminapi\controller\message;

use app\adminapi\service\message\SmsConfigService;
use app\adminapi\validate\message\SmsConfigValidate;
use app\common\service\sms\SmsConfigMapping;
use core\base\BaseAdminController;

/**
 * 短信配置控制器
 * Class SmsConfigController
 * @package app\adminapi\controller\message
 *
 * @OA\Tag(
 *     name="短信配置管理",
 *     description="短信配置相关接口"
 * )
 */
class SmsConfigController extends BaseAdminController
{
    /**
     * @Desc 短信配置列表
     * @Create on 2026/01/28
     *
     * @OA\Get(
     *     path="/message.smsConfig/list",
     *     summary="短信配置列表",
     *     tags={"短信配置管理"},
     *     security={{"token": {}}},
     *     @OA\Parameter(
     *         name="Token",
     *         in="header",
     *         description="登录Token",
     *         required=false,
     *         @OA\Schema(type="string")
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="成功响应",
     *         @OA\JsonContent(
     *             @OA\Property(property="code", type="integer", description="操作状态：0=失败 1=成功", example=1),
     *             @OA\Property(property="msg", type="string", example="获取成功"),
     *             @OA\Property(
     *                 property="data",
     *                 type="array",
     *                 @OA\Items(
     *                     type="object",
     *                     @OA\Property(property="id", type="integer", description="配置ID", example=1),
     *                     @OA\Property(property="gateway", type="string", description="网关标识", example="aliyun"),
     *                     @OA\Property(property="gateway_name", type="string", description="网关名称", example="阿里云短信"),
     *                     @OA\Property(property="config_data", type="object", description="配置数据"),
     *                     @OA\Property(property="is_default", type="integer", description="是否默认：0-否；1-是", example=1),
     *                     @OA\Property(property="create_time", type="integer", description="创建时间戳", example=1706428800)
     *                 )
     *             )
     *         )
     *     )
     * )
     */
    public function list()
    {
        $service = new SmsConfigService();
        $result = $service->getList();
        return success('获取成功', $result);
    }

    /**
     * @Desc 获取支持的短信网关列表
     * @Create on 2026/01/28
     *
     * @OA\Get(
     *     path="/message.smsConfig/gateways",
     *     summary="获取支持的短信网关列表",
     *     tags={"短信配置管理"},
     *     security={{"token": {}}},
     *     @OA\Parameter(
     *         name="Token",
     *         in="header",
     *         description="登录Token",
     *         required=false,
     *         @OA\Schema(type="string")
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="成功响应",
     *         @OA\JsonContent(
     *             @OA\Property(property="code", type="integer", description="操作状态：0=失败 1=成功", example=1),
     *             @OA\Property(property="msg", type="string", example="获取成功"),
     *             @OA\Property(
     *                 property="data",
     *                 type="array",
     *                 @OA\Items(
     *                     type="object",
     *                     @OA\Property(property="gateway", type="string", description="网关标识", example="aliyun"),
     *                     @OA\Property(property="gateway_name", type="string", description="网关名称", example="阿里云短信"),
     *                     @OA\Property(
     *                         property="required_fields",
     *                         type="array",
     *                         description="必填字段",
     *                         @OA\Items(type="string"),
     *                         example={"access_key_id", "access_key_secret", "sign_name"}
     *                     ),
     *                     @OA\Property(
     *                         property="optional_fields",
     *                         type="array",
     *                         description="可选字段",
     *                         @OA\Items(type="string"),
     *                         example={}
     *                     )
     *                 )
     *             )
     *         )
     *     )
     * )
     */
    public function gateways()
    {
        $gateways = [];
        foreach (SmsConfigMapping::GATEWAY_NAMES as $gateway => $name) {
            $gateways[] = [
                'gateway' => $gateway,
                'gateway_name' => $name,
                'required_fields' => SmsConfigMapping::GATEWAY_REQUIRED_FIELDS[$gateway] ?? [],
                'optional_fields' => SmsConfigMapping::GATEWAY_OPTIONAL_FIELDS[$gateway] ?? [],
            ];
        }
        return success('获取成功', $gateways);
    }

    /**
     * @Desc 查看短信配置详情
     * @Create on 2026/01/28
     *
     * @OA\Get(
     *     path="/message.smsConfig/detail",
     *     summary="查看短信配置详情",
     *     tags={"短信配置管理"},
     *     security={{"token": {}}},
     *     @OA\Parameter(
     *         name="Token",
     *         in="header",
     *         description="登录Token",
     *         required=false,
     *         @OA\Schema(type="string")
     *     ),
     *     @OA\Parameter(
     *         name="gateway",
     *         in="query",
     *         description="网关标识",
     *         required=true,
     *         @OA\Schema(type="string", example="aliyun")
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="成功响应",
     *         @OA\JsonContent(
     *             @OA\Property(property="code", type="integer", description="操作状态：0=失败 1=成功", example=1),
     *             @OA\Property(property="msg", type="string", example="获取成功"),
     *             @OA\Property(
     *                 property="data",
     *                 type="object",
     *                 @OA\Property(property="id", type="integer", description="配置ID", example=1),
     *                 @OA\Property(property="gateway", type="string", description="网关标识", example="aliyun"),
     *                 @OA\Property(property="gateway_name", type="string", description="网关名称", example="阿里云短信"),
     *                 @OA\Property(property="config_data", type="object", description="配置数据"),
     *                 @OA\Property(property="is_default", type="integer", description="是否默认：0-否；1-是", example=1),
     *                 @OA\Property(property="create_time", type="integer", description="创建时间戳", example=1706428800)
     *             )
     *         )
     *     )
     * )
     */
    public function detail()
    {
        $gateway = (string)$this->request->get('gateway', '');
        if ($gateway === '') {
            return fail('网关参数不能为空');
        }

        $service = new SmsConfigService();
        $result = $service->getConfig($gateway);
        return success('获取成功', $result);
    }

    /**
     * @Desc 保存短信配置
     * @Create on 2026/01/28
     *
     * @OA\Post(
     *     path="/message.smsConfig/save",
     *     summary="保存短信配置",
     *     tags={"短信配置管理"},
     *     security={{"token": {}}},
     *     @OA\Parameter(
     *         name="Token",
     *         in="header",
     *         description="登录Token",
     *         required=false,
     *         @OA\Schema(type="string")
     *     ),
     *     @OA\RequestBody(
     *         required=true,
     *         @OA\JsonContent(
     *             required={"gateway", "config_data"},
     *             @OA\Property(property="id", type="integer", description="配置ID（更新时传入）", example=1),
     *             @OA\Property(property="gateway", type="string", description="网关标识", maxLength=20, example="aliyun"),
     *             @OA\Property(
     *                 property="config_data",
     *                 type="object",
     *                 description="配置数据（根据不同网关要求的字段）",
     *                 example={"access_key_id": "your_key_id", "access_key_secret": "your_key_secret", "sign_name": "your_sign"}
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="成功响应",
     *         @OA\JsonContent(
     *             @OA\Property(property="code", type="integer", description="操作状态：0=失败 1=成功", example=1),
     *             @OA\Property(property="msg", type="string", example="保存成功"),
     *             @OA\Property(property="data", type="object")
     *         )
     *     )
     * )
     */
    public function save()
    {
        $data = (new SmsConfigValidate())->post()->goCheck('save');
        $service = new SmsConfigService();
        $id = isset($data['id']) ? (int)$data['id'] : null;
        $result = $service->saveConfig($data['gateway'], $data['config_data'], $id);

        if (!$result) {
            return fail($service->getError());
        }

        return success('保存成功');
    }

    /**
     * @Desc 切换默认短信网关
     * @Create on 2026/01/28
     *
     * @OA\Post(
     *     path="/message.smsConfig/switch",
     *     summary="切换默认短信网关",
     *     tags={"短信配置管理"},
     *     security={{"token": {}}},
     *     @OA\Parameter(
     *         name="Token",
     *         in="header",
     *         description="登录Token",
     *         required=false,
     *         @OA\Schema(type="string")
     *     ),
     *     @OA\RequestBody(
     *         required=true,
     *         @OA\JsonContent(
     *             required={"gateway"},
     *             @OA\Property(property="gateway", type="string", description="网关标识", example="aliyun")
     *         )
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="成功响应",
     *         @OA\JsonContent(
     *             @OA\Property(property="code", type="integer", description="操作状态：0=失败 1=成功", example=1),
     *             @OA\Property(property="msg", type="string", example="切换成功"),
     *             @OA\Property(property="data", type="object")
     *         )
     *     )
     * )
     */
    public function switch()
    {
        $gateway = (string)$this->request->post('gateway', '');
        if ($gateway === '') {
            return fail('网关参数不能为空');
        }

        $service = new SmsConfigService();
        $result = $service->switchGateway($gateway);

        if (!$result) {
            return fail($service->getError());
        }

        return success('切换成功');
    }

    /**
     * @Desc 测试短信配置连接
     * @Create on 2026/01/28
     *
     * @OA\Post(
     *     path="/message.smsConfig/test",
     *     summary="测试短信配置连接",
     *     tags={"短信配置管理"},
     *     security={{"token": {}}},
     *     @OA\Parameter(
     *         name="Token",
     *         in="header",
     *         description="登录Token",
     *         required=false,
     *         @OA\Schema(type="string")
     *     ),
     *     @OA\RequestBody(
     *         required=true,
     *         @OA\JsonContent(
     *             required={"gateway", "test_mobile"},
     *             @OA\Property(property="gateway", type="string", description="网关标识", example="aliyun"),
     *             @OA\Property(property="test_mobile", type="string", description="测试手机号", pattern="^1[3-9]\d{9}$", example="13800138000")
     *         )
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="成功响应",
     *         @OA\JsonContent(
     *             @OA\Property(property="code", type="integer", description="操作状态：0=失败 1=成功", example=1),
     *             @OA\Property(property="msg", type="string", example="测试短信发送成功"),
     *             @OA\Property(property="data", type="object")
     *         )
     *     )
     * )
     */
    public function test()
    {
        $data = (new SmsConfigValidate())->post()->goCheck('test');
        $service = new SmsConfigService();
        $result = $service->testConnection($data['gateway'], $data['test_mobile']);

        if (!$result['success']) {
            return fail($result['message']);
        }

        return success($result['message']);
    }

    /**
     * @Desc 删除短信配置
     * @Create on 2026/01/28
     *
     * @OA\Post(
     *     path="/message.smsConfig/delete",
     *     summary="删除短信配置",
     *     tags={"短信配置管理"},
     *     security={{"token": {}}},
     *     @OA\Parameter(
     *         name="Token",
     *         in="header",
     *         description="登录Token",
     *         required=false,
     *         @OA\Schema(type="string")
     *     ),
     *     @OA\RequestBody(
     *         required=true,
     *         @OA\JsonContent(
     *             @OA\Property(property="gateway", type="string", description="网关标识（gateway 和 id 至少传一个）", example="aliyun"),
     *             @OA\Property(property="id", type="integer", description="配置ID（gateway 和 id 至少传一个）", example=1)
     *         )
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="成功响应",
     *         @OA\JsonContent(
     *             @OA\Property(property="code", type="integer", description="操作状态：0=失败 1=成功", example=1),
     *             @OA\Property(property="msg", type="string", example="删除成功"),
     *             @OA\Property(property="data", type="object")
     *         )
     *     )
     * )
     */
    public function delete()
    {
        $gateway = (string)$this->request->post('gateway', '');
        $id = (int)$this->request->post('id', 0);
        if ($gateway === '' && $id <= 0) {
            return fail('网关参数不能为空');
        }

        $service = new SmsConfigService();
        $result = $service->deleteConfig($gateway, $id > 0 ? $id : null);

        if (!$result) {
            return fail($service->getError());
        }

        return success('删除成功');
    }
}