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 BackupsHandler {
  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_GetBackups>(
        'getBackups',
        async (dataArg) => {
          await requireValidIdentity(this.opsServerRef.adminHandler, dataArg);
          const backups = this.opsServerRef.oneboxRef.backupManager.listBackups();
          return { backups };
        },
      ),
    );

    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetBackup>(
        'getBackup',
        async (dataArg) => {
          await requireValidIdentity(this.opsServerRef.adminHandler, dataArg);
          const backup = this.opsServerRef.oneboxRef.database.getBackupById(dataArg.backupId);
          if (!backup) {
            throw new plugins.typedrequest.TypedResponseError('Backup not found');
          }
          return { backup };
        },
      ),
    );

    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_DeleteBackup>(
        'deleteBackup',
        async (dataArg) => {
          await requireValidIdentity(this.opsServerRef.adminHandler, dataArg);
          await this.opsServerRef.oneboxRef.backupManager.deleteBackup(dataArg.backupId);
          return { ok: true };
        },
      ),
    );

    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_RestoreBackup>(
        'restoreBackup',
        async (dataArg) => {
          await requireValidIdentity(this.opsServerRef.adminHandler, dataArg);
          const backupPath = this.opsServerRef.oneboxRef.backupManager.getBackupFilePath(dataArg.backupId);
          if (!backupPath) {
            throw new plugins.typedrequest.TypedResponseError('Backup file not found');
          }
          const rawResult = await this.opsServerRef.oneboxRef.backupManager.restoreBackup(
            backupPath,
            dataArg.options,
          );
          return {
            result: {
              service: {
                name: rawResult.service.name,
                status: rawResult.service.status,
              },
              platformResourcesRestored: rawResult.platformResourcesRestored,
              warnings: rawResult.warnings,
            },
          };
        },
      ),
    );

    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_DownloadBackup>(
        'downloadBackup',
        async (dataArg) => {
          await requireValidIdentity(this.opsServerRef.adminHandler, dataArg);
          const backup = this.opsServerRef.oneboxRef.database.getBackupById(dataArg.backupId);
          if (!backup) {
            throw new plugins.typedrequest.TypedResponseError('Backup not found');
          }
          const filePath = this.opsServerRef.oneboxRef.backupManager.getBackupFilePath(dataArg.backupId);
          if (!filePath) {
            throw new plugins.typedrequest.TypedResponseError('Backup file not found');
          }
          // Return a download URL that the client can fetch directly
          return {
            downloadUrl: `/api/backups/${dataArg.backupId}/download`,
            filename: backup.filename,
          };
        },
      ),
    );
  }
}
