/**
 * @aurora-catalyst-generated
 * @source cliter/iam/account.aurora.yaml
 */
import { IamAccount, IamCreateAccountInput, IamUpdateAccountByIdInput } from '@api/graphql';
import { IamAccountModel } from '@app/iam/account';
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 IamSequelizeAccountRepository extends SequelizeCatalystRepository<
  IamAccountModel,
  IamAccount
> {
  constructor(
    @InjectModel(IamAccountModel)
    public readonly repository: typeof IamAccountModel,
    public readonly criteria: ICriteria,
    public readonly auditingRunner: AuditingRunner,
  ) {
    super();
  }

  // hook called after create aggregate
  async createdAggregateHook(
    aggregate: IamCreateAccountInput,
    model: IamAccountModel,
    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] IamSequelizeAccountRepository:', error);
      }
    }
    if (Array.isArray(aggregate?.tenantIds) && aggregate.tenantIds.length > 0) {
      try {
        await model.$add('tenants', aggregate.tenantIds, createOptions);
      } catch (error) {
        console.error('[Error] IamSequelizeAccountRepository:', error);
      }
    }
  }

  // hook called after create aggregate
  async updatedByIdAggregateHook(
    aggregate: IamUpdateAccountByIdInput,
    model: IamAccountModel,
    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] IamSequelizeAccountRepository:', error);
      }
    }
    if (Array.isArray(aggregate?.tenantIds)) {
      try {
        await model.$set('tenants', aggregate.tenantIds, updateByIdOptions);
      } catch (error) {
        console.error('[Error] IamSequelizeAccountRepository:', error);
      }
    }
  }
}
