import type { IncomingMessage, ServerResponse } from 'node:http'; import type { GatewayAutoService } from '../../features/routing/index.js'; import { HarborError } from '../../../shared/errors.js'; import { sendJson } from '../response.js'; interface GatewayAutoRouteDependencies { appMode: string; gatewayAuto: Pick; readBody(req: IncomingMessage): Promise>; withOperation(kind: string, operation: () => Promise): Promise; readStatePayload(): Promise & { gatewayAuto?: unknown }>; } export function createGatewayAutoRoute(dependencies: GatewayAutoRouteDependencies) { return { async handle(req: IncomingMessage, res: ServerResponse) { if (req.method !== 'POST' || req.url !== '/api/gateway-auto') return false; if (dependencies.appMode !== 'client') throw new HarborError('REQUEST_INVALID'); const { enabled } = await dependencies.readBody(req); if (typeof enabled !== 'boolean') throw new HarborError('REQUEST_INVALID'); await dependencies.withOperation( 'gateway-auto', () => dependencies.gatewayAuto.setEnabled(enabled), ); const state = await dependencies.readStatePayload(); sendJson(res, 200, { success: true, gatewayAuto: state.gatewayAuto, state }); return true; }, }; }