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

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

  private registerHandlers(): void {
    const pm = () => this.opsServerRef.objectStorageRef.policyManager;

    // List named policies
    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_ListNamedPolicies>(
        'listNamedPolicies',
        async (dataArg) => {
          await requireValidIdentity(this.opsServerRef.adminHandler, dataArg);
          return { policies: pm().listPolicies() };
        },
      ),
    );

    // Create named policy
    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_CreateNamedPolicy>(
        'createNamedPolicy',
        async (dataArg) => {
          await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
          const policy = await pm().createPolicy(dataArg.name, dataArg.description, dataArg.statements);
          await this.opsServerRef.objectStorageRef.auditLogger.log({
            actorUserId: dataArg.identity.userId,
            action: 'policy.create',
            targetType: 'policy',
            targetId: policy.id,
            success: true,
          });
          return { policy };
        },
      ),
    );

    // Update named policy
    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_UpdateNamedPolicy>(
        'updateNamedPolicy',
        async (dataArg) => {
          await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
          const policy = await pm().updatePolicy(dataArg.policyId, dataArg.name, dataArg.description, dataArg.statements);
          await this.opsServerRef.objectStorageRef.auditLogger.log({
            actorUserId: dataArg.identity.userId,
            action: 'policy.update',
            targetType: 'policy',
            targetId: dataArg.policyId,
            success: true,
          });
          return { policy };
        },
      ),
    );

    // Delete named policy
    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_DeleteNamedPolicy>(
        'deleteNamedPolicy',
        async (dataArg) => {
          await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
          await pm().deletePolicy(dataArg.policyId);
          await this.opsServerRef.objectStorageRef.auditLogger.log({
            actorUserId: dataArg.identity.userId,
            action: 'policy.delete',
            targetType: 'policy',
            targetId: dataArg.policyId,
            success: true,
          });
          return { ok: true };
        },
      ),
    );

    // Get bucket named policies (attached + available)
    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetBucketNamedPolicies>(
        'getBucketNamedPolicies',
        async (dataArg) => {
          await requireValidIdentity(this.opsServerRef.adminHandler, dataArg);
          return pm().getBucketAttachments(dataArg.bucketName);
        },
      ),
    );

    // Attach policy to bucket
    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_AttachPolicyToBucket>(
        'attachPolicyToBucket',
        async (dataArg) => {
          await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
          await pm().attachPolicyToBucket(dataArg.policyId, dataArg.bucketName);
          await this.opsServerRef.objectStorageRef.auditLogger.log({
            actorUserId: dataArg.identity.userId,
            action: 'policy.attach',
            targetType: 'bucket',
            targetId: dataArg.bucketName,
            success: true,
            metadata: { policyId: dataArg.policyId },
          });
          return { ok: true };
        },
      ),
    );

    // Detach policy from bucket
    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_DetachPolicyFromBucket>(
        'detachPolicyFromBucket',
        async (dataArg) => {
          await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
          await pm().detachPolicyFromBucket(dataArg.policyId, dataArg.bucketName);
          await this.opsServerRef.objectStorageRef.auditLogger.log({
            actorUserId: dataArg.identity.userId,
            action: 'policy.detach',
            targetType: 'bucket',
            targetId: dataArg.bucketName,
            success: true,
            metadata: { policyId: dataArg.policyId },
          });
          return { ok: true };
        },
      ),
    );

    // Get policy buckets (attached + available)
    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetPolicyBuckets>(
        'getPolicyBuckets',
        async (dataArg) => {
          await requireValidIdentity(this.opsServerRef.adminHandler, dataArg);
          const attachedBuckets = pm().getBucketsForPolicy(dataArg.policyId);
          const allBuckets = await this.opsServerRef.objectStorageRef.listBuckets();
          const attachedSet = new Set(attachedBuckets);
          const availableBuckets = allBuckets
            .map((b) => b.name)
            .filter((name) => !attachedSet.has(name));
          return { attachedBuckets, availableBuckets };
        },
      ),
    );

    // Set policy buckets
    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_SetPolicyBuckets>(
        'setPolicyBuckets',
        async (dataArg) => {
          await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
          await pm().setPolicyBuckets(dataArg.policyId, dataArg.bucketNames);
          await this.opsServerRef.objectStorageRef.auditLogger.log({
            actorUserId: dataArg.identity.userId,
            action: 'policy.setBuckets',
            targetType: 'policy',
            targetId: dataArg.policyId,
            success: true,
            metadata: { bucketCount: dataArg.bucketNames.length },
          });
          return { ok: true };
        },
      ),
    );
  }
}
