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 SendTemplateMessageSchema = z.object({
  openid: z.string().min(1, 'openid不能为空'),
  templateId: z.string().min(1, '模板ID不能为空'),
  page: z.string().optional().default('pages/index/index'),
  data: z.record(z.string(), z.object({
    value: z.string()
  })),
  miniprogramState: z.enum(['developer', 'trial', 'formal']).optional().default('formal'),
  tenantId: z.number().optional()
});

// 微信模板消息响应Schema
const SendTemplateMessageResponseSchema = z.object({
  success: z.boolean(),
  message: z.string(),
  data: z.any().optional(),
  error: z.any().optional()
});

const sendTemplateMessageRoute = createRoute({
  method: 'post',
  path: '/send-template-message',
  request: {
    body: {
      content: {
        'application/json': {
          schema: SendTemplateMessageSchema
        }
      }
    }
  },
  responses: {
    200: {
      description: '微信模板消息发送成功',
      content: {
        'application/json': {
          schema: SendTemplateMessageResponseSchema
        }
      }
    },
    400: {
      description: '参数错误',
      content: {
        'application/json': {
          schema: ErrorSchema
        }
      }
    },
    500: {
      description: '服务器错误',
      content: {
        'application/json': {
          schema: ErrorSchema
        }
      }
    }
  }
});

const app = new OpenAPIHono().openapi(sendTemplateMessageRoute, async (c) => {
  try {
    const miniAuthService = new MiniAuthService(AppDataSource);
    const { openid, templateId, page, data, miniprogramState, tenantId } = c.req.valid('json');

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

    console.log('收到微信模板消息发送请求:', {
      openid,
      templateId,
      page,
      dataKeys: Object.keys(data),
      miniprogramState,
      tenantId,
      timestamp
    });

    // 调用服务发送模板消息
    const result = await miniAuthService.sendTemplateMessage({
      openid,
      templateId,
      page,
      data: data as Record<string, { value: string }>,
      miniprogramState,
      tenantId
    });

    return c.json({
      success: true,
      message: '微信模板消息发送成功',
      data: result
    }, 200);

  } catch (error) {
    console.error('发送微信模板消息失败:', error);

    const errorMessage = error instanceof Error ? error.message : '发送微信模板消息失败';
    const errorCode = (error as any)?.code || 500;

    return c.json({
      success: false,
      message: errorMessage,
      error: error instanceof Error ? error.stack : error
    }, errorCode);
  }
});

export default app;