"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.updateAvailabilitySigns = exports.addAvailabilitySign = exports.getAvailabilitySigns = exports.findAvailabilitySignsByBBCDateId = void 0;
const mongoose_1 = __importDefault(require("mongoose"));
const AvailabilitySigns_model_1 = require("../models/AvailabilitySigns.model");
const findAvailabilitySignsByBBCDateId = async (bbcDateId) => {
    return AvailabilitySigns_model_1.AvailabilitySignsModel.findOne({ bbcDateId: new mongoose_1.default.Types.ObjectId(bbcDateId) }).lean();
};
exports.findAvailabilitySignsByBBCDateId = findAvailabilitySignsByBBCDateId;
const getAvailabilitySigns = async (bbcDateIds, repo = AvailabilitySigns_model_1.AvailabilitySignsModel) => {
    return repo.find({ bbcDateId: { $in: bbcDateIds } }).lean();
};
exports.getAvailabilitySigns = getAvailabilitySigns;
const addAvailabilitySign = async (bbcDateId, sign) => {
    const availabilitySigns = await AvailabilitySigns_model_1.AvailabilitySignsModel.findOne({ bbcDateId: new mongoose_1.default.Types.ObjectId(bbcDateId) }).lean();
    if (!availabilitySigns) {
        await AvailabilitySigns_model_1.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 AvailabilitySigns_model_1.AvailabilitySignsModel.findOneAndUpdate({ bbcDateId: new mongoose_1.default.Types.ObjectId(bbcDateId) }, { signs: [...updatedSigns, sign] });
    return { message: 'Availability was signed', success: true };
};
exports.addAvailabilitySign = addAvailabilitySign;
const updateAvailabilitySigns = async (bbcDateId, signs) => {
    await AvailabilitySigns_model_1.AvailabilitySignsModel.findOneAndUpdate({ bbcDateId: new mongoose_1.default.Types.ObjectId(bbcDateId) }, { signs: signs });
};
exports.updateAvailabilitySigns = updateAvailabilitySigns;
