// media-router.js
// Copyright (C) 2022 DTP Technologies, LLC
// License: Apache-2.0

'use strict';

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const STATUS_LIST = [
  'starting',   // the router process is starting and configuring itself
  'active',     // the router is active and available for service
  'capacity',   // the router is at or over capacity
  'closing',    // the router is closing/shutting down
  'closed',     // the router no longer exists
];

const RouterHostSchema = new Schema({
  address: { type: String, required: true, index: 1 },
  port: { type: Number, required: true },
});

/*
 * A Router is a "multi-user conference call instance" somewhere on the
 * infrastructure. This model helps us manage them, balance load across them,
 * and route calls to and between them (for scale).
 * 
 * These records are created when a call is being created, and are commonly
 * left in the database after all call participants have left. An expires index
 * is used to sweep up router records after 30 days. This allows us to perform
 * statistics aggregation on router use and store aggregated results as part of
 * long-term reporting.
 */
const MediaRouterSchema = new Schema({
  created: { type: Date, default: Date.now, required: true, expires: '30d' },
  lastActivity: { type: Date, default: Date.now, required: true },
  status: { type: String, enum: STATUS_LIST, default: 'starting', required: true, index: true },
  name: { type: String },
  description: { type: String },
  access: {
    isPrivate: { type: Boolean, default: true, required: true },
    passcodeHash: { type: String, select: false },
  },
  host: { type: RouterHostSchema, required: true, select: false },
  stats: {
    routerCount: { type: Number, default: 0, required: true },
    consumerCount: { type: Number, default: 0, required: true },
    producerCount: { type: Number, default: 0, required: true },
  }
});

module.exports = mongoose.model('MediaRouter', MediaRouterSchema);