/**
 * @aurora-catalyst-generated
 * @source cliter/iam/permission.aurora.yaml
 */
import {
  IamCreatePermissionInput,
  IamPermission,
  IamUpdatePermissionByIdInput,
} from '@api/graphql';
import { IamPermissionModel } from '@app/iam/permission';
import { AuditingRunner, ICriteria, SequelizeCatalystRepository } from '@aurorajs.dev/core-back';
import { LiteralObject } from '@aurorajs.dev/core-common';
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/sequelize';

@Injectable()
export class IamSequelizePermissionRepository extends SequelizeCatalystRepository<
  IamPermissionModel,
  IamPermission
> {
  constructor(
    @InjectModel(IamPermissionModel)
    public readonly repository: typeof IamPermissionModel,
    public readonly criteria: ICriteria,
    public readonly auditingRunner: AuditingRunner,
  ) {
    super();
  }

  // hook called after create aggregate
  async createdAggregateHook(
    aggregate: IamCreatePermissionInput,
    model: IamPermissionModel,
    createOptions: LiteralObject,
  ): Promise<void> {
    // add many to many relation
    if (Array.isArray(aggregate?.roleIds) && aggregate.roleIds.length > 0) {
      try {
        await model.$add('roles', aggregate.roleIds, createOptions);
      } catch (error) {
        console.error('[Error] IamSequelizePermissionRepository:', error);
      }
    }
  }

  // hook called after create aggregate
  async updatedByIdAggregateHook(
    aggregate: IamUpdatePermissionByIdInput,
    model: IamPermissionModel,
    updateByIdOptions: LiteralObject,
  ): Promise<void> {
    // set many to many relation
    if (Array.isArray(aggregate?.roleIds)) {
      try {
        await model.$set('roles', aggregate.roleIds, updateByIdOptions);
      } catch (error) {
        console.error('[Error] IamSequelizePermissionRepository:', error);
      }
    }
  }
}
