import * as plugins from '../../plugins.js';
import type { OpsServer } from '../classes.opsserver.js';
import * as interfaces from '../../../ts_interfaces/index.js';
import { requireOpsAuth } from '../helpers/auth.js';

export class RouteManagementHandler {
  public typedrouter = new plugins.typedrequest.TypedRouter();

  constructor(private opsServerRef: OpsServer) {
    this.opsServerRef.typedrouter.addTypedRouter(this.typedrouter);
    this.registerHandlers();
  }

  /**
   * Validate auth: JWT identity OR API token with required scope.
   * Returns a userId string on success, throws on failure.
   */
  private async requireAuth(
    request: { identity?: interfaces.data.IIdentity; apiToken?: string },
    requiredScope?: interfaces.data.TApiTokenScope,
  ): Promise<string> {
    const auth = await requireOpsAuth(this.opsServerRef, request, {
      scope: requiredScope,
      requireAdminIdentity: requiredScope?.endsWith(':write'),
    });
    return auth.userId;
  }

  private registerHandlers(): void {
    // Get merged routes
    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetMergedRoutes>(
        'getMergedRoutes',
        async (dataArg) => {
          await this.requireAuth(dataArg, 'routes:read');
          const manager = this.opsServerRef.dcRouterRef.routeConfigManager;
          if (!manager) {
            return { routes: [], warnings: [] };
          }
          return manager.getMergedRoutes();
        },
      ),
    );

    // Create route
    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_CreateRoute>(
        'createRoute',
        async (dataArg) => {
          const userId = await this.requireAuth(dataArg, 'routes:write');
          const manager = this.opsServerRef.dcRouterRef.routeConfigManager;
          if (!manager) {
            return { success: false, message: 'Route management not initialized' };
          }
          const id = await manager.createRoute(dataArg.route, userId, dataArg.enabled ?? true, dataArg.metadata);
          return { success: true, routeId: id };
        },
      ),
    );

    // Update route
    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_UpdateRoute>(
        'updateRoute',
        async (dataArg) => {
          await this.requireAuth(dataArg, 'routes:write');
          const manager = this.opsServerRef.dcRouterRef.routeConfigManager;
          if (!manager) {
            return { success: false, message: 'Route management not initialized' };
          }
          const result = await manager.updateRoute(dataArg.id, {
            route: dataArg.route as any,
            enabled: dataArg.enabled,
            metadata: dataArg.metadata,
          });
          return result;
        },
      ),
    );

    // Delete route
    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_DeleteRoute>(
        'deleteRoute',
        async (dataArg) => {
          await this.requireAuth(dataArg, 'routes:write');
          const manager = this.opsServerRef.dcRouterRef.routeConfigManager;
          if (!manager) {
            return { success: false, message: 'Route management not initialized' };
          }
          return manager.deleteRoute(dataArg.id);
        },
      ),
    );

    // Toggle route
    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_ToggleRoute>(
        'toggleRoute',
        async (dataArg) => {
          await this.requireAuth(dataArg, 'routes:write');
          const manager = this.opsServerRef.dcRouterRef.routeConfigManager;
          if (!manager) {
            return { success: false, message: 'Route management not initialized' };
          }
          return manager.toggleRoute(dataArg.id, dataArg.enabled);
        },
      ),
    );
  }
}
