import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { z } from 'zod';
import { AppDataSource, parseWithAwait } from '@d8d/shared-utils';
import { authMiddleware } from '@d8d/auth-module-mt';
import { AuthContext } from '@d8d/shared-types';
import { DelaySchedulerService } from '../../services/delay-scheduler.service';

// 手动触发调度器响应Schema
const TriggerSchedulerResponseSchema = z.object({
  success: z.boolean(),
  data: z.object({
    processedTasks: z.number(),
    successfulTasks: z.number(),
    failedTasks: z.number(),
    executionTime: z.number(),
    tenantId: z.number()
  })
});

// 手动触发调度器路由定义
const triggerSchedulerRoute = createRoute({
  method: 'post',
  path: '/trigger',
  middleware: [authMiddleware],
  responses: {
    200: {
      description: '调度器手动触发成功',
      content: { 'application/json': { schema: TriggerSchedulerResponseSchema } }
    },
    401: {
      description: '未授权',
      content: { 'application/json': { schema: z.object({ message: z.string() }) } }
    },
    500: {
      description: '服务器错误',
      content: { 'application/json': { schema: z.object({ success: z.boolean(), message: z.string() }) } }
    }
  }
});

const app = new OpenAPIHono<AuthContext>()
  .openapi(triggerSchedulerRoute, async (c) => {
    const user = c.get('user');
    const tenantId = user?.tenantId || 1;

    // 创建租户特定的调度器实例
    const delaySchedulerService = new DelaySchedulerService(AppDataSource, {
      baseUrl: 'https://api.feieyun.cn/Api/Open/',
      user: '',
      ukey: '',
      timeout: 10000,
      maxRetries: 3
    }, tenantId);

    const result = await delaySchedulerService.triggerManualProcess();

    // 验证响应格式
    const response = {
      success: result.success,
      data: {
        processedTasks: result.processedTasks,
        successfulTasks: result.processedTasks, // 假设所有处理的任务都成功
        failedTasks: 0, // 目前没有失败计数
        executionTime: 0, // 目前没有执行时间
        tenantId
      }
    };
    const validatedResponse = await parseWithAwait(TriggerSchedulerResponseSchema, response);

    return c.json(validatedResponse, 200);
  });

export default app;