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 } from '../schemas';

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

const getBalanceRoutes = new OpenAPIHono<AuthContext>()
  .openapi(getBalanceRoute, async (c) => {
    const user = c.get('user');
    const userId = parseInt(c.req.param('userId'));

    try {
      const service = new CreditBalanceService(AppDataSource);
      const balance = await service.getBalance(user.tenantId, userId);
      if (!balance) {
        return c.json({ code: 404, message: '用户信用额度记录不存在' }, 404);
      }

      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 getBalanceRoutes;