/**
 * @aurora-catalyst-generated
 * @source cliter/o-auth/application.aurora.yaml
 */
import {
  OAuthApplication,
  OAuthCreateApplicationInput,
  OAuthUpdateApplicationByIdInput,
} from '@api/graphql';
import { OAuthApplicationModel } from '@app/o-auth/application';
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 OAuthSequelizeApplicationRepository extends SequelizeCatalystRepository<
  OAuthApplicationModel,
  OAuthApplication
> {
  constructor(
    @InjectModel(OAuthApplicationModel)
    public readonly repository: typeof OAuthApplicationModel,
    public readonly criteria: ICriteria,
    public readonly auditingRunner: AuditingRunner,
  ) {
    super();
  }

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

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