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 { CreditBalanceLogSchema, QueryBalanceLogsDto } from '../schemas';

const getBalanceLogsRoute = createRoute({
  method: 'get',
  path: '/{userId}/logs',
  middleware: [authMiddleware],
  request: {
    params: z.object({
      userId: z.string().openapi({
        param: {
          name: 'userId',
          in: 'path'
        },
        description: '用户ID',
        example: '1001'
      })
    }),
    query: QueryBalanceLogsDto
  },
  responses: {
    200: {
      description: '获取额度变更记录成功',
      content: {
        'application/json': {
          schema: z.object({
            data: z.array(CreditBalanceLogSchema),
            pagination: z.object({
              page: z.number(),
              pageSize: z.number(),
              total: z.number(),
              totalPages: z.number()
            })
          })
        }
      }
    },
    400: {
      description: '请求参数错误',
      content: {
        'application/json': {
          schema: ErrorSchema
        }
      }
    },
    401: {
      description: '认证失败',
      content: {
        'application/json': {
          schema: ErrorSchema
        }
      }
    },
    403: {
      description: '权限不足',
      content: {
        'application/json': {
          schema: ErrorSchema
        }
      }
    },
    500: {
      description: '服务器内部错误',
      content: {
        'application/json': {
          schema: ErrorSchema
        }
      }
    }
  }
});

const getBalanceLogsRoutes = new OpenAPIHono<AuthContext>()
  .openapi(getBalanceLogsRoute, async (c) => {
    const user = c.get('user');
    const userId = parseInt(c.req.param('userId'));
    const query = c.req.valid('query');

    try {
      const service = new CreditBalanceService(AppDataSource);
      const page = query.page || 1;
      const pageSize = query.pageSize || 20;

      const [logs, total] = await service.getBalanceLogs(
        user.tenantId,
        userId,
        page,
        pageSize
      );

      const responseData = await parseWithAwait(
        z.object({
          data: z.array(CreditBalanceLogSchema),
          pagination: z.object({
            page: z.number(),
            pageSize: z.number(),
            total: z.number(),
            totalPages: z.number()
          })
        }),
        {
          data: logs,
          pagination: {
            page,
            pageSize,
            total,
            totalPages: Math.ceil(total / pageSize)
          }
        }
      );

      return c.json(responseData, 200);
    } catch (error) {
      console.error('获取额度变更记录失败:', error);
      return c.json(
        { code: 500, message: error instanceof Error ? error.message : '获取额度变更记录失败' },
        500
      );
    }
  });

export default getBalanceLogsRoutes;