const hash = require('../../utils/hash');
const mongoose = require('mongoose');
const {ObjectId} = mongoose.SchemaTypes;
const moment = require('moment');
const _ = require('lodash');

const schema = mongoose.Schema({
    platform: {
        type: String,
        required: true
    },
    releaseStat: {
        type: Object,
        default: {}
    },
    refreshing: Boolean,
    account: {
        type: String
        // required: true
    },
    tags: {
        type: [String],
        default: []
    },
    authRoles: {
        stat: {
            type: [String],
            default: []
        },
        publish: {
            type: [String],
            default: []
        },
        into: {
            type: [String],
            default: []
        },
        distribution: {
            type: [String],
            default: []
        },
        income: {
            type: [String],
            default: []
        }
    },
    extra: String,
    source: String,
    avatar: String,
    password: String,
    nickname: String,
    custom: String,
    session: Array,
    creater: ObjectId,
    automatic: Boolean,
    category: String,
    status: String,
    oAuth: {}
}, {
    timestamps: true
});

schema.index({account: 1, platform: 1});
schema.pre('save', function (next) {
    this.set('_id', mongoose.Types.ObjectId(
        hash(this.platform + ':' + this.account).slice(0, 12))
    );
    next();
});

schema.virtual('release')
    .get(function () {
        const key = moment().format('YYYYMMDD');
        return this.releaseStat[key] || {};
    })
    .set(function (value) {
        if (!value.date) throw Error('release 没有 date 字段');
        const doc = this.toJSON();
        const key = moment(value.date).format('YYYYMMDD');
        this.releaseStat = _.merge(doc.releaseStat, {
            [key]: _.omit(value, 'date')
        });
    });

module.exports = mongoose.model('upstream', schema);
