import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { z } from '@hono/zod-openapi';
import { MiniAuthService } from '../services/index.mt';
import { AppDataSource } from '@d8d/shared-utils';
import { ErrorSchema } from '@d8d/shared-utils';

// 获取交易管理状态请求Schema
const GetIsTradeManagedSchema = z.object({
  tenantId: z.number().optional()
});

// 交易管理状态响应Schema
const IsTradeManagedResponseSchema = z.object({
  success: z.boolean(),
  message: z.string(),
  data: z.object({
    is_trade_managed: z.boolean()
  }).optional(),
  error: z.any().optional()
});

const getIsTradeManagedRoute = createRoute({
  method: 'post',
  path: '/get-is-trade-managed',
  request: {
    body: {
      content: {
        'application/json': {
          schema: GetIsTradeManagedSchema
        }
      }
    }
  },
  responses: {
    200: {
      description: '获取交易管理状态成功',
      content: {
        'application/json': {
          schema: IsTradeManagedResponseSchema
        }
      }
    },
    400: {
      description: '参数错误',
      content: {
        'application/json': {
          schema: ErrorSchema
        }
      }
    },
    500: {
      description: '服务器错误',
      content: {
        'application/json': {
          schema: ErrorSchema
        }
      }
    }
  }
});

const app = new OpenAPIHono().openapi(getIsTradeManagedRoute, async (c) => {
  try {
    const miniAuthService = new MiniAuthService(AppDataSource);
    const { tenantId } = c.req.valid('json');

    // 调试输出
    const timestamp = new Date().toISOString();

    console.log('收到获取交易管理状态请求:', {
      tenantId,
      timestamp
    });

    // 调用服务获取交易管理状态
    const result = await miniAuthService.getIsTradeManaged(tenantId);

    // 检查返回的数据结构
    if (typeof result.is_trade_managed !== 'boolean') {
      console.warn('微信API返回的交易管理状态格式不正确:', result);
      return c.json({
        code: 500,
        message: '交易管理状态格式不正确'
      }, 500);
    }

    return c.json({
      success: true,
      message: '获取交易管理状态成功',
      data: {
        is_trade_managed: result.is_trade_managed
      }
    }, 200);

  } catch (error) {
    console.error('获取交易管理状态失败:', error);

    const errorMessage = error instanceof Error ? error.message : '获取交易管理状态失败';
    const errorCode = (error as any)?.code || 500;

    return c.json({
      code: errorCode,
      message: errorMessage
    }, errorCode);
  }
});

export default app;