const Framework = require("../../framework/node-core-framework.js");
const authorizationService = require('../services/authorization_service.js');

/**
 * 账号管理控制器（客户端接口）
 * 提供客户端调用的账号相关接口
 */
module.exports = {
  /**
   * @swagger
   * /api/account/check-authorization:
   *   post:
   *     summary: 检查账号授权状态
   *     description: 根据设备SN码检查账号的授权状态（剩余天数、是否过期等）
   *     tags: [前端-账号管理]
   *     requestBody:
   *       required: true
   *       content:
   *         application/json:
   *           schema:
   *             type: object
   *             required:
   *               - sn_code
   *             properties:
   *               sn_code:
   *                 type: string
   *                 description: 设备SN码
   *                 example: 'GHJU'
   *     responses:
   *       200:
   *         description: 检查成功
   *         content:
   *           application/json:
   *             schema:
   *               type: object
   *               properties:
   *                 code:
   *                   type: integer
   *                   description: 状态码，0表示成功
   *                   example: 0
   *                 message:
   *                   type: string
   *                   description: 响应消息
   *                   example: 'success'
   *                 data:
   *                   type: object
   *                   properties:
   *                     is_authorized:
   *                       type: boolean
   *                       description: 是否已授权
   *                       example: true
   *                     remaining_days:
   *                       type: integer
   *                       description: 剩余天数
   *                       example: 30
   *                     message:
   *                       type: string
   *                       description: 授权状态消息
   *                       example: '授权有效，剩余 30 天'
   *       400:
   *         description: 参数错误
   *         content:
   *           application/json:
   *             schema:
   *               type: object
   *               properties:
   *                 code:
   *                   type: integer
   *                   example: 400
   *                 message:
   *                   type: string
   *                   example: '请提供设备SN码'
   *       500:
   *         description: 服务器错误
   */
  'POST /account/check-authorization': async (ctx) => {
    try {
      const { sn_code } = ctx.getBody();

      // 参数验证
      if (!sn_code) {
        return ctx.fail('请提供设备SN码');
      }

      // 调用授权服务检查授权状态
      const result = await authorizationService.checkAuthorization(sn_code, 'sn_code');

      // 返回授权检查结果
      return ctx.success({
        is_authorized: result.is_authorized,
        remaining_days: result.remaining_days,
        message: result.message
      });
    } catch (error) {
      console.error('[账号管理] 检查授权状态失败:', error);
      return ctx.fail('检查授权状态失败: ' + (error.message || '未知错误'));
    }
  }
};

