const mongoose = require('mongoose');
mongoose.set('useFindAndModify', false);
//mongoose.set('debug', true)

const provisionSchema = new mongoose.Schema({
    user: {
        type: mongoose.Types.ObjectId, 
        ref: 'User',
        index: true
    },
    created: {
        type: Date,
        default: Date.now,
        index : true
    },
    updated: {
        type: Date,
        default: Date.now
    },
    scenario: {
        type: String,
        required: true
    },
    scenarioVersion: {
        type: String,
        default: "1.0"
    },
    description: String,
    vmImage: Object,
    status: {
        type: String,
        default: "queued"
    },
    jobId: String,
    logFile: String,
    outputs: Object,
    path: String,
    isExternalAccess: {
        type: Boolean,
        default: false
    },
    barracudaAppId: {
        type: String
    },
    barracudaAppCname: {
        type: String
    },
    barracudaAzureFqdn: {
        type: String
    },
    isDestroyed: {
        type: Boolean,
        default: false
    },
    isDeleted: {
        type: Boolean,
        default: false,
        index: true
    },
    statusVms: {
        type: String
    },
    destroy: {
        type: mongoose.Types.ObjectId, ref: 'Destroy'
    },
    actualDestroyDate: {
        type: Date
    },
    runningFrom: {
        type: Date
    },
    stoppedFrom: {
        type: Date
    },
    timeRunning: {
        type: Number,
        default: 0
    },
    startDateOnSchedule: {
        type: Date
    },
    endDateOnSchedule: {
        type: Date
    },
    countExtend: {
        type: Number,
        default: 0
    },
    pendingNextAction: {
        type: String
    },
    schedule: {
        type: mongoose.Types.ObjectId, 
        ref: 'Schedule'
    },
    deployOpts: {
        type: mongoose.Types.ObjectId, 
        ref: "Subscription"
    },
    terraformImage: {
        type: String
    },
    version: {
        type: Number
    },
    parent: {
        type: mongoose.Types.ObjectId, 
        ref: 'Provision'
    }
},{
    toObject: {virtuals:true},
    toJSON: {virtuals:true},
});

// Foreign keys definitions

provisionSchema.virtual('_scenarioDoc', {
    ref: 'Scenario',
    localField: 'scenario',
    foreignField: 'name',
    justOne: true // for many-to-1 relationships
});

module.exports = mongoose.model('Provision', provisionSchema)