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 StartSchedulerResponseSchema = z.object({
  success: z.boolean(),
  message: z.string()
});

// 启动调度器路由定义
const startSchedulerRoute = createRoute({
  method: 'post',
  path: '/start',
  middleware: [authMiddleware],
  responses: {
    200: {
      description: '调度器启动成功',
      content: { 'application/json': { schema: StartSchedulerResponseSchema } }
    },
    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(startSchedulerRoute, 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);

    await delaySchedulerService.start();

    // 验证响应格式
    const response = {
      success: true as const,
      message: '调度器已启动'
    };
    const validatedResponse = await parseWithAwait(StartSchedulerResponseSchema, response);

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

export default app;