import { createRoute, OpenAPIHono } 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 meRoute = createRoute({
  method: 'get',
  path: '/me',
  middleware: [authMiddleware],
  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 meRoutes = new OpenAPIHono<AuthContext>()
  .openapi(meRoute, async (c) => {
    const user = c.get('user');

    try {
      const service = new CreditBalanceService(AppDataSource);
      const balance = await service.getBalance(user.tenantId, user.id);
      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 meRoutes;