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 SchedulerStatusResponseSchema = z.object({
  success: z.boolean(),
  data: z.object({
    isRunning: z.boolean(),
    lastRunTime: z.string().nullable(),
    nextRunTime: z.string().nullable(),
    processedTasks: z.number(),
    failedTasks: z.number(),
    pendingTasks: z.number(),
    tenantId: z.number()
  })
});

// 调度器状态路由定义
const schedulerStatusRoute = createRoute({
  method: 'get',
  path: '/status',
  middleware: [authMiddleware],
  responses: {
    200: {
      description: '调度器状态获取成功',
      content: { 'application/json': { schema: SchedulerStatusResponseSchema } }
    },
    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(schedulerStatusRoute, 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 status = delaySchedulerService.getStatus();

    // 验证响应格式
    const response = {
      success: true as const,
      data: {
        isRunning: status.isRunning,
        lastRunTime: status.lastProcessTime ? status.lastProcessTime.toISOString() : null,
        nextRunTime: null, // 需要从服务获取
        processedTasks: 0, // 需要从服务获取
        failedTasks: 0, // 需要从服务获取
        pendingTasks: 0, // 需要从服务获取
        tenantId: status.tenantId
      }
    };
    const validatedResponse = await parseWithAwait(SchedulerStatusResponseSchema, response);

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

export default app;