/**
 * Config API Routes
 *
 * 配置管理相关的 REST API
 */

import { Hono } from 'hono';

export const configRouter = new Hono();

// 服务器配置
interface ServerConfig {
  workdir: string;
}

let serverConfig: ServerConfig = {
  workdir: process.cwd(),
};

/**
 * GET /config - 获取当前配置
 */
configRouter.get('/', (c) => {
  return c.json({
    success: true,
    data: serverConfig,
  });
});

/**
 * PUT /config - 更新配置
 */
configRouter.put('/', async (c) => {
  try {
    const body = await c.req.json();

    // 合并配置 (只更新提供的字段)
    serverConfig = {
      ...serverConfig,
      ...body,
    };

    return c.json({
      success: true,
      data: serverConfig,
    });
  } catch (error) {
    return c.json(
      {
        success: false,
        error: error instanceof Error ? error.message : 'Invalid input',
      },
      400
    );
  }
});

/**
 * PATCH /config - 部分更新配置
 */
configRouter.patch('/', async (c) => {
  try {
    const body = await c.req.json();

    // 部分更新
    Object.keys(body).forEach((key) => {
      if (key in serverConfig) {
        (serverConfig as any)[key] = body[key];
      }
    });

    return c.json({
      success: true,
      data: serverConfig,
    });
  } catch (error) {
    return c.json(
      {
        success: false,
        error: error instanceof Error ? error.message : 'Invalid input',
      },
      400
    );
  }
});

/**
 * 获取当前配置 (内部使用)
 */
export function getConfig(): ServerConfig {
  return { ...serverConfig };
}

/**
 * 设置配置 (内部使用)
 */
export function setConfig(config: Partial<ServerConfig>): void {
  serverConfig = { ...serverConfig, ...config };
}
