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 NetworkTargetHandler {
  public typedrouter = new plugins.typedrequest.TypedRouter();

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

  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 all network targets
    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetNetworkTargets>(
        'getNetworkTargets',
        async (dataArg) => {
          await this.requireAuth(dataArg, 'targets:read');
          const resolver = this.opsServerRef.dcRouterRef.referenceResolver;
          if (!resolver) {
            return { targets: [] };
          }
          return { targets: resolver.listTargets() };
        },
      ),
    );

    // Get a single network target
    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetNetworkTarget>(
        'getNetworkTarget',
        async (dataArg) => {
          await this.requireAuth(dataArg, 'targets:read');
          const resolver = this.opsServerRef.dcRouterRef.referenceResolver;
          if (!resolver) {
            return { target: null };
          }
          return { target: resolver.getTarget(dataArg.id) || null };
        },
      ),
    );

    // Create a network target
    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_CreateNetworkTarget>(
        'createNetworkTarget',
        async (dataArg) => {
          const userId = await this.requireAuth(dataArg, 'targets:write');
          const resolver = this.opsServerRef.dcRouterRef.referenceResolver;
          if (!resolver) {
            return { success: false, message: 'Reference resolver not initialized' };
          }
          const id = await resolver.createTarget({
            name: dataArg.name,
            description: dataArg.description,
            host: dataArg.host,
            port: dataArg.port,
            createdBy: userId,
          });
          return { success: true, id };
        },
      ),
    );

    // Update a network target
    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_UpdateNetworkTarget>(
        'updateNetworkTarget',
        async (dataArg) => {
          await this.requireAuth(dataArg, 'targets:write');
          const resolver = this.opsServerRef.dcRouterRef.referenceResolver;
          const manager = this.opsServerRef.dcRouterRef.routeConfigManager;
          if (!resolver || !manager) {
            return { success: false, message: 'Not initialized' };
          }

          const { affectedRouteIds } = await resolver.updateTarget(dataArg.id, {
            name: dataArg.name,
            description: dataArg.description,
            host: dataArg.host,
            port: dataArg.port,
          });

          if (affectedRouteIds.length > 0) {
            await manager.reResolveRoutes(affectedRouteIds);
          }

          return { success: true, affectedRouteCount: affectedRouteIds.length };
        },
      ),
    );

    // Delete a network target
    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_DeleteNetworkTarget>(
        'deleteNetworkTarget',
        async (dataArg) => {
          await this.requireAuth(dataArg, 'targets:write');
          const resolver = this.opsServerRef.dcRouterRef.referenceResolver;
          const manager = this.opsServerRef.dcRouterRef.routeConfigManager;
          if (!resolver || !manager) {
            return { success: false, message: 'Not initialized' };
          }

          const result = await resolver.deleteTarget(
            dataArg.id,
            dataArg.force ?? false,
            manager.getRoutes(),
          );

          if (result.success && dataArg.force) {
            await manager.applyRoutes();
          }

          return result;
        },
      ),
    );

    // Get routes using a network target
    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetNetworkTargetUsage>(
        'getNetworkTargetUsage',
        async (dataArg) => {
          await this.requireAuth(dataArg, 'targets:read');
          const resolver = this.opsServerRef.dcRouterRef.referenceResolver;
          const manager = this.opsServerRef.dcRouterRef.routeConfigManager;
          if (!resolver || !manager) {
            return { routes: [] };
          }
          const usage = resolver.getTargetUsageForId(dataArg.id, manager.getRoutes());
          return { routes: usage.map((u) => ({ id: u.id, name: u.routeName })) };
        },
      ),
    );
  }
}
