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 SchedulerHealthResponseSchema = z.object({
  success: z.boolean(),
  data: z.object({
    isHealthy: z.boolean(),
    status: z.string(),
    lastCheckTime: z.string(),
    errors: z.array(z.string()).optional(),
    tenantId: z.number()
  })
});

// 调度器健康检查路由定义
const schedulerHealthRoute = createRoute({
  method: 'get',
  path: '/health',
  middleware: [authMiddleware],
  responses: {
    200: {
      description: '调度器健康检查成功',
      content: { 'application/json': { schema: SchedulerHealthResponseSchema } }
    },
    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(schedulerHealthRoute, 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 health = await delaySchedulerService.healthCheck();

    // 验证响应格式
    const response = {
      success: true as const,
      data: {
        isHealthy: health.healthy,
        status: health.isRunning ? 'RUNNING' : 'STOPPED',
        lastCheckTime: health.timestamp.toISOString(),
        errors: health.lastError ? [health.lastError] : [],
        tenantId
      }
    };
    const validatedResponse = await parseWithAwait(SchedulerHealthResponseSchema, response);

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

export default app;