import * as plugins from '../../plugins.js';
import type { OpsServer } from '../classes.opsserver.js';
import * as interfaces from '../../../ts_interfaces/index.js';
import { requireAdminIdentity } from '../helpers/guards.js';
import { getErrorMessage } from '../../utils/error.js';

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

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

  private registerHandlers(): void {
    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetSystemStatus>(
        'getSystemStatus',
        async (dataArg) => {
          await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
          const status = await this.opsServerRef.oneboxRef.getSystemStatus();
          return { status: status as unknown as interfaces.data.ISystemStatus };
        },
      ),
    );

    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_StartOneboxUpgrade>(
        'startOneboxUpgrade',
        async (dataArg) => {
          await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
          try {
            const upgrade = await this.opsServerRef.oneboxRef.updateManager.startDetachedUpgrade();
            return { upgrade };
          } catch (error) {
            throw new plugins.typedrequest.TypedResponseError(getErrorMessage(error));
          }
        },
      ),
    );
  }
}
