import * as Models from '../..//lib/models/models';
import mongoose = require( 'mongoose' );

export default class MongooseDeletes {
  public models: Models.MongooseModels;

  public constructor( models: Models.MongooseModels ) {
    this.models = models;
  }

  // /**
  //  * Get report by id
  //  */
  // public async deleteReportById( reportId: ObjectId ): Promise<void> {
  //   const canConnect = await this.mongoDbConnection.canConnect();
  //   if ( !canConnect ) {
  //     return null;
  //   }
  //   // await this.mongoDbConnection._connectToDatabase();
  //   return this.mongoDbConnection
  //     ._connectToDatabase()
  //     .then( () => this.mongoDbConnection._initializeCollections() )
  //     .then( () => this._deleteReportById( reportId ) )
  //     .then( ( report ) => {
  //       this.mongoDbConnection.connection.close();
  //       return report;
  //     } );
  // }

  /**
   * Get one element from mongodb database by id
   *
   * @param {object} options JSON object with the options
   * @private
   */
  public async deleteReportById( id: mongoose.Types.ObjectId | string ): Promise<void> {
    const oId: mongoose.Types.ObjectId = typeof id === 'string' ? new mongoose.Types.ObjectId( id ) : id;
    // const sortObj = { index: 1 };

    await this.models.reportModel.deleteOne( { _id: oId } );
    const features = await this.models.featureModel.find( { reportId: oId } );

    await Promise.all(
      features.map( async ( feature ) => {
        const scenariosLocal = await this.models.scenarioModel.find( { featureId: feature._id as mongoose.Types.ObjectId } );
        await Promise.all(
          scenariosLocal.map( async ( scenario ) => {
            await this.models.stepModel.deleteMany( { scenarioId: scenario._id as mongoose.Types.ObjectId } );
          } )
        );
        await this.models.scenarioModel.deleteMany( { featureId: scenariosLocal[0]?.featureId } );
      } )
    );
    await this.models.featureModel.deleteMany( { reportId: oId } );
    await this.models.reportModel.deleteOne( { _id: oId } );
  }
}
