import { AvailabilitySignsModel } from '../models/AvailabilitySigns.model';

import { CollateralsService } from './collaterals.service';

export class LockService {
  constructor(
    private readonly collateralsService: CollateralsService,
  ) {
  }

  async isDateLocked(checkDate: Date, borrowerId: string) {
    const bbcDocsAfter = await this.collateralsService.gebNextBBC(borrowerId, checkDate);
    const activeSignsAfter = await AvailabilitySignsModel.aggregate([
      {
        $match: {
          'bbcDateId': { $in: bbcDocsAfter.map((bbc) => bbc._id) },
        },
      }, {
        $unwind: {
          path: '$signs',
          preserveNullAndEmptyArrays: true,
        },
      }, {
        $match: {
          'signs.revokedAt': {
            $exists: false,
          },
        },
      }, {
        $group: {
          '_id': '$_id',
          'requiredSigns': { $first: '$requiredSigns' },
          'signs': { $push: '$signs' },
        },
      }, {
        $match: {
          $expr: {
            $gte: [{ '$size': '$signs' }, '$requiredSigns'],
          },
        },
      },
    ]);
    return activeSignsAfter.length > 0;
  }
}
