import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { z } from '@hono/zod-openapi';
import { authMiddleware } from '@d8d/core-module-mt/auth-module-mt/middleware';
import { AppDataSource, ErrorSchema, parseWithAwait } from '@d8d/shared-utils';
import { AuthContext } from '@d8d/shared-types';
import { CreditBalanceService } from '../services';
import { CreditBalanceSchema, AdjustLimitDto } from '../schemas';

const adjustLimitRoute = createRoute({
  method: 'post',
  path: '/{userId}/adjust',
  middleware: [authMiddleware],
  request: {
    params: z.object({
      userId: z.string().openapi({
        param: {
          name: 'userId',
          in: 'path'
        },
        description: '用户ID',
        example: '1001'
      })
    }),
    body: {
      content: {
        'application/json': {
          schema: AdjustLimitDto
        }
      }
    }
  },
  responses: {
    200: {
      description: '调整用户信用额度成功',
      content: {
        'application/json': {
          schema: CreditBalanceSchema
        }
      }
    },
    400: {
      description: '请求参数错误'
    },
    401: {
      description: '认证失败'
    },
    403: {
      description: '权限不足'
    },
    500: {
      description: '服务器内部错误'
    }
  }
});

const adjustLimitRoutes = new OpenAPIHono<AuthContext>()
  .openapi(adjustLimitRoute, async (c) => {
    const user = c.get('user');
    const userId = parseInt(c.req.param('userId'));
    const data = c.req.valid('json');

    try {
      const service = new CreditBalanceService(AppDataSource);
      const balance = await service.adjustLimit({
        tenantId: user.tenantId,
        userId,
        adjustAmount: data.adjustAmount,
        operatorId: data.operatorId,
        remark: data.remark
      });

      const responseData = await parseWithAwait(CreditBalanceSchema, balance);
      return c.json(responseData, 200);
    } catch (error) {
      console.error('调整用户信用额度失败:', error);
      return c.json(
        { code: 500, message: error instanceof Error ? error.message : '调整用户信用额度失败' },
        500
      );
    }
  });

export default adjustLimitRoutes;