import * as plugins from '../../plugins.ts';
import type { OpsServer } from '../classes.opsserver.ts';
import * as interfaces from '../../../ts_interfaces/index.ts';
import { requireValidIdentity } from '../helpers/guards.ts';

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

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

  private registerHandlers(): void {
    // Force scan secrets
    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_ForceScanSecrets>(
        'forceScanSecrets',
        async (dataArg) => {
          await requireValidIdentity(this.opsServerRef.adminHandler, dataArg);
          const scanService = this.opsServerRef.gitopsAppRef.secretsScanService;
          const result = await scanService.fullScan();
          return {
            ok: true,
            connectionsScanned: result.connectionsScanned,
            secretsFound: result.secretsFound,
            errors: result.errors,
            durationMs: result.durationMs,
          };
        },
      ),
    );

    // Get scan status
    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetScanStatus>(
        'getScanStatus',
        async (dataArg) => {
          await requireValidIdentity(this.opsServerRef.adminHandler, dataArg);
          const scanService = this.opsServerRef.gitopsAppRef.secretsScanService;
          return {
            lastScanTimestamp: scanService.lastScanTimestamp,
            isScanning: scanService.isScanning,
            lastResult: scanService.lastScanResult,
          };
        },
      ),
    );
  }
}
