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 CredentialsHandler {
  public typedrouter = new plugins.typedrequest.TypedRouter();

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

  private registerHandlers(): void {
    // Get credentials (secrets masked)
    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetCredentials>(
        'getCredentials',
        async (dataArg) => {
          await requireValidIdentity(this.opsServerRef.adminHandler, dataArg);
          const activeCredentials = await this.opsServerRef.objectStorageRef
            .listAccessCredentials();
          const credentials = activeCredentials.map(
            (cred) => ({
              accessKeyId: cred.accessKeyId,
              secretAccessKey: '********',
            }),
          );
          return { credentials };
        },
      ),
    );

    // Add credential
    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_AddCredential>(
        'addCredential',
        async (dataArg) => {
          await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
          const credentials = this.opsServerRef.objectStorageRef.config.accessCredentials;
          if (credentials.some((credential) => credential.accessKeyId === dataArg.accessKeyId)) {
            throw new plugins.typedrequest.TypedResponseError('Credential already exists');
          }

          try {
            await this.opsServerRef.objectStorageRef.replaceAccessCredentials([
              ...credentials,
              {
                accessKeyId: dataArg.accessKeyId,
                secretAccessKey: dataArg.secretAccessKey,
              },
            ]);
            await this.opsServerRef.objectStorageRef.auditLogger.log({
              actorUserId: dataArg.identity.userId,
              action: 'credential.add',
              targetType: 'credential',
              targetId: dataArg.accessKeyId,
              success: true,
            });
          } catch (error) {
            await this.opsServerRef.objectStorageRef.auditLogger.log({
              actorUserId: dataArg.identity.userId,
              action: 'credential.add',
              targetType: 'credential',
              targetId: dataArg.accessKeyId,
              success: false,
              message: error instanceof Error ? error.message : String(error),
            });
            throw error;
          }
          return { ok: true };
        },
      ),
    );

    // Remove credential
    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_RemoveCredential>(
        'removeCredential',
        async (dataArg) => {
          await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
          const creds = this.opsServerRef.objectStorageRef.config.accessCredentials;
          if (!creds.some((credential) => credential.accessKeyId === dataArg.accessKeyId)) {
            throw new plugins.typedrequest.TypedResponseError('Credential not found');
          }
          if (creds.length <= 1) {
            throw new plugins.typedrequest.TypedResponseError(
              'Cannot remove the last credential',
            );
          }
          try {
            await this.opsServerRef.objectStorageRef.replaceAccessCredentials(
              creds.filter((credential) => credential.accessKeyId !== dataArg.accessKeyId),
            );
            await this.opsServerRef.objectStorageRef.auditLogger.log({
              actorUserId: dataArg.identity.userId,
              action: 'credential.remove',
              targetType: 'credential',
              targetId: dataArg.accessKeyId,
              success: true,
            });
          } catch (error) {
            await this.opsServerRef.objectStorageRef.auditLogger.log({
              actorUserId: dataArg.identity.userId,
              action: 'credential.remove',
              targetType: 'credential',
              targetId: dataArg.accessKeyId,
              success: false,
              message: error instanceof Error ? error.message : String(error),
            });
            throw error;
          }
          return { ok: true };
        },
      ),
    );
  }
}
