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 { CreditBalanceChangeType } from '../entities';
import { CreditBalanceSchema, CheckoutDto } from '../schemas';

const checkoutRoute = createRoute({
  method: 'post',
  path: '/checkout',
  middleware: [authMiddleware],
  request: {
    body: {
      content: {
        'application/json': {
          schema: CheckoutDto
        }
      }
    }
  },
  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
        }
      }
    },
    500: {
      description: '服务器内部错误',
      content: {
        'application/json': {
          schema: ErrorSchema
        }
      }
    }
  }
});

const checkoutRoutes = new OpenAPIHono<AuthContext>()
  .openapi(checkoutRoute, async (c) => {
    const user = c.get('user');
    const data = c.req.valid('json');

    try {
      const service = new CreditBalanceService(AppDataSource);
      const balance = await service.restoreAmount({
        tenantId: user.tenantId,
        userId: data.userId,
        amount: data.amount,
        changeType: CreditBalanceChangeType.CHECKOUT,
        referenceId: data.referenceId,
        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 checkoutRoutes;