/**
 * @aurora-catalyst-generated
 * @source cliter/iam/tenant.aurora.yaml
 */
import { IamCreateTenantInput, IamTenant, IamUpdateTenantByIdInput } from '@api/graphql';
import { IamTenantModel } from '@app/iam/tenant';
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 IamSequelizeTenantRepository extends SequelizeCatalystRepository<
  IamTenantModel,
  IamTenant
> {
  constructor(
    @InjectModel(IamTenantModel)
    public readonly repository: typeof IamTenantModel,
    public readonly criteria: ICriteria,
    public readonly auditingRunner: AuditingRunner,
  ) {
    super();
  }

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

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