/**
 * @aurora-catalyst-generated
 * @source cliter/iam/role.aurora.yaml
 */
import { IamCreateRoleInput, IamRole, IamUpdateRoleByIdInput } from '@api/graphql';
import { IamRoleModel } from '@app/iam/role';
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 IamSequelizeRoleRepository extends SequelizeCatalystRepository<IamRoleModel, IamRole> {
  constructor(
    @InjectModel(IamRoleModel)
    public readonly repository: typeof IamRoleModel,
    public readonly criteria: ICriteria,
    public readonly auditingRunner: AuditingRunner,
  ) {
    super();
  }

  // hook called after create aggregate
  async createdAggregateHook(
    aggregate: IamCreateRoleInput,
    model: IamRoleModel,
    createOptions: LiteralObject,
  ): Promise<void> {
    // add many to many relation
    if (Array.isArray(aggregate?.permissionIds) && aggregate.permissionIds.length > 0) {
      try {
        await model.$add('permissions', aggregate.permissionIds, createOptions);
      } catch (error) {
        console.error('[Error] IamSequelizeRoleRepository:', error);
      }
    }
    if (Array.isArray(aggregate?.accountIds) && aggregate.accountIds.length > 0) {
      try {
        await model.$add('accounts', aggregate.accountIds, createOptions);
      } catch (error) {
        console.error('[Error] IamSequelizeRoleRepository:', error);
      }
    }
  }

  // hook called after create aggregate
  async updatedByIdAggregateHook(
    aggregate: IamUpdateRoleByIdInput,
    model: IamRoleModel,
    updateByIdOptions: LiteralObject,
  ): Promise<void> {
    // set many to many relation
    if (Array.isArray(aggregate?.permissionIds)) {
      try {
        await model.$set('permissions', aggregate.permissionIds, updateByIdOptions);
      } catch (error) {
        console.error('[Error] IamSequelizeRoleRepository:', error);
      }
    }
    if (Array.isArray(aggregate?.accountIds)) {
      try {
        await model.$set('accounts', aggregate.accountIds, updateByIdOptions);
      } catch (error) {
        console.error('[Error] IamSequelizeRoleRepository:', error);
      }
    }
  }
}
