/**
 * @aurora-catalyst-generated
 * @source cliter/o-auth/client.aurora.yaml
 */
import { OAuthClient, OAuthCreateClientInput, OAuthUpdateClientByIdInput } from '@api/graphql';
import { OAuthClientModel } from '@app/o-auth/client';
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 OAuthSequelizeClientRepository extends SequelizeCatalystRepository<
  OAuthClientModel,
  OAuthClient
> {
  constructor(
    @InjectModel(OAuthClientModel)
    public readonly repository: typeof OAuthClientModel,
    public readonly criteria: ICriteria,
    public readonly auditingRunner: AuditingRunner,
  ) {
    super();
  }

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

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