import { createRoute, OpenAPIHono, z } from '@hono/zod-openapi';
import { SystemSettingSchema } from '@/server/modules/settings/system-setting.schema';
import { BatchUpdateSettingsDto } from '@/server/modules/settings/system-setting.schema';
import { ErrorSchema } from '@/server/utils/errorHandler';
import { AppDataSource } from '@/server/data-source';
import { SystemSettingService } from '@/server/modules/settings/system-setting.service';
import { AuthContext } from '@/server/types/context';
import { authMiddleware } from '@/server/middleware/auth.middleware';

// 响应Schema
const BatchUpdateResponse = z.object({
  data: z.array(SystemSettingSchema),
  updated: z.number().openapi({ example: 3, description: '成功更新的设置数量' })
});

// 路由定义
const routeDef = createRoute({
  method: 'put',
  path: '/batch',
  middleware: [authMiddleware],
  request: {
    body: {
      content: {
        'application/json': { schema: BatchUpdateSettingsDto }
      }
    }
  },
  responses: {
    200: {
      description: '成功批量更新系统设置',
      content: { 'application/json': { schema: BatchUpdateResponse } }
    },
    400: {
      description: '请求参数错误',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '服务器错误',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

// 路由实现
const app = new OpenAPIHono<AuthContext>().openapi(routeDef, async (c) => {
  try {
    const { settings } = await c.req.json();
    
    const service = new SystemSettingService(AppDataSource);
    const results = await service.batchUpdate(settings);
    
    return c.json({
      data: results,
      updated: results.length
    }, 200);
  } catch (error) {
    const { code = 500, message = '批量更新系统设置失败' } = error as Error & { code?: number };
    return c.json({ code, message }, code);
  }
});

export default app;