import mongoose from 'mongoose';

import {
  AvailabilitySignsModel,
  IAvailabilitySignItem,
} from '../models/AvailabilitySigns.model';
import { IResult } from '../interfaces/result.interface';

export const findAvailabilitySignsByBBCDateId = async (bbcDateId: string) => {
  return AvailabilitySignsModel.findOne({ bbcDateId: new mongoose.Types.ObjectId(bbcDateId) }).lean();
};

export const getAvailabilitySigns = async (bbcDateIds: string[], repo = AvailabilitySignsModel) => {
  return repo.find({ bbcDateId: { $in: bbcDateIds } }).lean();
};

export const addAvailabilitySign = async (bbcDateId: string, sign: IAvailabilitySignItem): Promise<IResult> => {
  const availabilitySigns = await AvailabilitySignsModel.findOne({ bbcDateId: new mongoose.Types.ObjectId(bbcDateId) }).lean();
  if (!availabilitySigns) {
    await AvailabilitySignsModel.create({ bbcDateId, signs: [sign] });
    return { message: 'Availability was signed', success: true };
  }
  const activeSigns = availabilitySigns.signs.filter((sign) => !sign.revokedAt);
  const foundUserSign = activeSigns.find((s) => s.userSignedId.toString() === sign.userSignedId.toString());
  if (foundUserSign) {
    return { message: `You already signed this availability`, success: false };
  }
  if (activeSigns.length >= availabilitySigns.requiredSigns) {
    return { message: `Availability required only ${availabilitySigns.requiredSigns} signs`, success: false };
  }
  const updatedSigns = availabilitySigns.signs.slice();
  await AvailabilitySignsModel.findOneAndUpdate({ bbcDateId: new mongoose.Types.ObjectId(bbcDateId) }, { signs: [...updatedSigns, sign] });
  return { message: 'Availability was signed', success: true };
};

export const updateAvailabilitySigns = async (bbcDateId: string, signs: IAvailabilitySignItem[]): Promise<void> => {
  await AvailabilitySignsModel.findOneAndUpdate({ bbcDateId: new mongoose.Types.ObjectId(bbcDateId) }, { signs: signs });
};
