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

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

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

  private registerHandlers(): void {
    // List objects
    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_ListObjects>(
        'listObjects',
        async (dataArg) => {
          await requireValidIdentity(this.opsServerRef.adminHandler, dataArg);
          const result = await this.opsServerRef.objectStorageRef.listObjects(
            dataArg.bucketName,
            dataArg.prefix,
            dataArg.delimiter,
            dataArg.maxKeys,
          );
          return { result };
        },
      ),
    );

    // Delete object
    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_DeleteObject>(
        'deleteObject',
        async (dataArg) => {
          await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
          await this.opsServerRef.objectStorageRef.deleteObject(dataArg.bucketName, dataArg.key);
          await this.opsServerRef.objectStorageRef.auditLogger.log({
            actorUserId: dataArg.identity.userId,
            action: 'object.delete',
            targetType: 'object',
            targetId: `${dataArg.bucketName}/${dataArg.key}`,
            success: true,
          });
          return { ok: true };
        },
      ),
    );

    // Get object
    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetObject>(
        'getObject',
        async (dataArg) => {
          await requireValidIdentity(this.opsServerRef.adminHandler, dataArg);
          return await this.opsServerRef.objectStorageRef.getObject(dataArg.bucketName, dataArg.key);
        },
      ),
    );

    // Put object
    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_PutObject>(
        'putObject',
        async (dataArg) => {
          await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
          await this.opsServerRef.objectStorageRef.putObject(
            dataArg.bucketName,
            dataArg.key,
            dataArg.base64Content,
            dataArg.contentType,
          );
          await this.opsServerRef.objectStorageRef.auditLogger.log({
            actorUserId: dataArg.identity.userId,
            action: 'object.put',
            targetType: 'object',
            targetId: `${dataArg.bucketName}/${dataArg.key}`,
            success: true,
          });
          return { ok: true };
        },
      ),
    );

    // Delete prefix (folder)
    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_DeletePrefix>(
        'deletePrefix',
        async (dataArg) => {
          await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
          await this.opsServerRef.objectStorageRef.deletePrefix(dataArg.bucketName, dataArg.prefix);
          await this.opsServerRef.objectStorageRef.auditLogger.log({
            actorUserId: dataArg.identity.userId,
            action: 'objectPrefix.delete',
            targetType: 'objectPrefix',
            targetId: `${dataArg.bucketName}/${dataArg.prefix}`,
            success: true,
          });
          return { ok: true };
        },
      ),
    );

    // Get object URL
    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetObjectUrl>(
        'getObjectUrl',
        async (dataArg) => {
          await requireValidIdentity(this.opsServerRef.adminHandler, dataArg);
          const url = await this.opsServerRef.objectStorageRef.getObjectUrl(dataArg.bucketName, dataArg.key);
          return { url };
        },
      ),
    );

    // Move object
    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_MoveObject>(
        'moveObject',
        async (dataArg) => {
          await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
          const result = await this.opsServerRef.objectStorageRef.moveObject(
            dataArg.bucketName,
            dataArg.sourceKey,
            dataArg.destKey,
          );
          await this.opsServerRef.objectStorageRef.auditLogger.log({
            actorUserId: dataArg.identity.userId,
            action: 'object.move',
            targetType: 'object',
            targetId: `${dataArg.bucketName}/${dataArg.sourceKey}`,
            success: result.success,
            metadata: { destKey: dataArg.destKey },
            message: result.error,
          });
          return result;
        },
      ),
    );

    // Move prefix (folder)
    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_MovePrefix>(
        'movePrefix',
        async (dataArg) => {
          await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
          const result = await this.opsServerRef.objectStorageRef.movePrefix(
            dataArg.bucketName,
            dataArg.sourcePrefix,
            dataArg.destPrefix,
          );
          await this.opsServerRef.objectStorageRef.auditLogger.log({
            actorUserId: dataArg.identity.userId,
            action: 'objectPrefix.move',
            targetType: 'objectPrefix',
            targetId: `${dataArg.bucketName}/${dataArg.sourcePrefix}`,
            success: result.success,
            metadata: { destPrefix: dataArg.destPrefix },
            message: result.error,
          });
          return result;
        },
      ),
    );
  }
}
