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 SourceProfileHandler {
  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 source profiles
    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetSourceProfiles>(
        'getSourceProfiles',
        async (dataArg) => {
          await this.requireAuth(dataArg, 'source-profiles:read');
          const resolver = this.opsServerRef.dcRouterRef.referenceResolver;
          if (!resolver) {
            return { profiles: [] };
          }
          return { profiles: resolver.listProfiles() };
        },
      ),
    );

    // Get a single source profile
    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetSourceProfile>(
        'getSourceProfile',
        async (dataArg) => {
          await this.requireAuth(dataArg, 'source-profiles:read');
          const resolver = this.opsServerRef.dcRouterRef.referenceResolver;
          if (!resolver) {
            return { profile: null };
          }
          return { profile: resolver.getProfile(dataArg.id) || null };
        },
      ),
    );

    // Create a source profile
    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_CreateSourceProfile>(
        'createSourceProfile',
        async (dataArg) => {
          const userId = await this.requireAuth(dataArg, 'source-profiles:write');
          const resolver = this.opsServerRef.dcRouterRef.referenceResolver;
          if (!resolver) {
            return { success: false, message: 'Reference resolver not initialized' };
          }
          const id = await resolver.createProfile({
            name: dataArg.name,
            description: dataArg.description,
            security: dataArg.security,
            extendsProfiles: dataArg.extendsProfiles,
            createdBy: userId,
          });
          return { success: true, id };
        },
      ),
    );

    // Update a source profile
    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_UpdateSourceProfile>(
        'updateSourceProfile',
        async (dataArg) => {
          await this.requireAuth(dataArg, 'source-profiles: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.updateProfile(dataArg.id, {
            name: dataArg.name,
            description: dataArg.description,
            security: dataArg.security,
            extendsProfiles: dataArg.extendsProfiles,
          });

          // Propagate to affected routes
          if (affectedRouteIds.length > 0) {
            await manager.reResolveRoutes(affectedRouteIds);
          }

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

    // Delete a source profile
    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_DeleteSourceProfile>(
        'deleteSourceProfile',
        async (dataArg) => {
          await this.requireAuth(dataArg, 'source-profiles: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.deleteProfile(
            dataArg.id,
            dataArg.force ?? false,
            manager.getRoutes(),
          );

          // If force-deleted with affected routes, re-apply
          if (result.success && dataArg.force) {
            await manager.applyRoutes();
          }

          return result;
        },
      ),
    );

    // Get routes using a source profile
    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetSourceProfileUsage>(
        'getSourceProfileUsage',
        async (dataArg) => {
          await this.requireAuth(dataArg, 'source-profiles:read');
          const resolver = this.opsServerRef.dcRouterRef.referenceResolver;
          const manager = this.opsServerRef.dcRouterRef.routeConfigManager;
          if (!resolver || !manager) {
            return { routes: [] };
          }
          const usage = resolver.getProfileUsageForId(dataArg.id, manager.getRoutes());
          return { routes: usage.map((u) => ({ id: u.id, name: u.routeName })) };
        },
      ),
    );
  }
}
