"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.DailySignalCacheService = void 0;
const mongoose_1 = __importDefault(require("mongoose"));
const DailySignalCacheModel_js_1 = require("../../infrastructure/database/models/DailySignalCacheModel.js");
const random_js_1 = require("../../shared/utils/random.js");
class DailySignalCacheService {
    platformCode;
    memoryCache = new Map();
    constructor(platformCode) {
        this.platformCode = platformCode;
    }
    async getOrCreateDailyRecords(category, networkCode, generator) {
        const date = todayUtc();
        const cacheKey = `${this.platformCode}:${category}:${networkCode ?? "ANY"}:${date}`;
        if (!this.isDatabaseConnected()) {
            const cached = this.memoryCache.get(cacheKey);
            if (cached && cached.length > 0)
                return cached;
            const records = await generator(category, networkCode);
            this.memoryCache.set(cacheKey, records);
            return records;
        }
        const cacheQuery = {
            platformCode: this.platformCode,
            category,
            date,
            networkCode: networkCode ?? "ANY"
        };
        const cached = await DailySignalCacheModel_js_1.DailySignalCacheModel.findOne(cacheQuery).lean();
        if (cached && cached.records.length > 0) {
            return cached.records;
        }
        const records = await generator(category, networkCode);
        try {
            await DailySignalCacheModel_js_1.DailySignalCacheModel.findOneAndUpdate(cacheQuery, { ...cacheQuery, records }, { upsert: true, returnDocument: "after" });
        }
        catch (error) {
            // Race condition: another process inserted the cache between findOne and findOneAndUpdate.
            // Return the existing cached records instead.
            const existing = await DailySignalCacheModel_js_1.DailySignalCacheModel.findOne(cacheQuery).lean();
            if (existing && existing.records.length > 0) {
                return existing.records;
            }
            throw error;
        }
        return records;
    }
    pickRandom(records) {
        return (0, random_js_1.chooseOne)(records);
    }
    isDatabaseConnected() {
        return mongoose_1.default.connection.readyState === 1;
    }
}
exports.DailySignalCacheService = DailySignalCacheService;
const todayUtc = () => {
    const now = new Date();
    return `${now.getUTCFullYear()}-${String(now.getUTCMonth() + 1).padStart(2, "0")}-${String(now.getUTCDate()).padStart(2, "0")}`;
};
