/**
 * ######################################################################
 * #                                                                    #
 * #                       Do not change the file!                      #
 * #                                                                    #
 * # All changes are deleted the next time the collection data is read. #
 * #                                                                    #
 * ######################################################################
 */

import { Connection, model, Schema } from 'mongoose';

import { {{collectionNameLower}}Definitions, {{collectionNameLower}}Indexes } from '../documents/{{collectionNameLower}}';
import { {{interfaceName}}{{collectionNameUpper}}Document, {{interfaceName}}{{collectionNameUpper}}Model } from '../interfaces/{{collectionNameLower}}';
import { methods, options, queries, statics, virtuals } from '../repositories/{{collectionNameLower}}';

import { addIndexes, addVirtualProperties, checkDuplicateKeys } from '../helper';

// If a key was found several times, then an error is thrown.
checkDuplicateKeys('{{collectionNameLower}}', [Schema.prototype, {{collectionNameLower}}Definitions, methods, statics, queries, virtuals])

// Create model schema
export const {{collectionNameLower}}Schema = new Schema({{collectionNameLower}}Definitions, options);

{{collectionNameLower}}Schema.methods = { ...methods, ...{{collectionNameLower}}Schema.methods };
{{collectionNameLower}}Schema.statics = { ...statics, ...{{collectionNameLower}}Schema.statics };
{{collectionNameLower}}Schema.query = { ...queries, ...{{collectionNameLower}}Schema.query };
addVirtualProperties({{collectionNameLower}}Schema, virtuals);
addIndexes({{collectionNameLower}}Schema, {{collectionNameLower}}Indexes);

/**
 * For multiple database connections
 *
 * @param handler
 * @param collection
 */
export const create{{collectionNameUpper}}Model = (handler: Connection) => {
  return handler.model<{{interfaceName}}{{collectionNameUpper}}Document, {{interfaceName}}{{collectionNameUpper}}Model>(
    '{{collectionNameUpper}}',
    {{collectionNameLower}}Schema
  );
};

/**
 * Create default model with default connection
 */
const Model = model<{{interfaceName}}{{collectionNameUpper}}Document, {{interfaceName}}{{collectionNameUpper}}Model>(
  '{{collectionNameUpper}}',
  {{collectionNameLower}}Schema,
);

export default Model;
