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

// 停止调度器路由定义
const stopSchedulerRoute = createRoute({
  method: 'post',
  path: '/stop',
  middleware: [authMiddleware],
  responses: {
    200: {
      description: '调度器停止成功',
      content: { 'application/json': { schema: StopSchedulerResponseSchema } }
    },
    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(stopSchedulerRoute, 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.stop();

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

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

export default app;