/********* START OF METHOD LOGIC *********/
/**
  * Auto-fill system data
  */

{{#if ENTITY_META.is_creatable}}
data.app = authData?.current?.app?._id
  ? authData?.current?.app?._id
  : opt?.bypassAuthorization ||
      (authData?.current?.service?.name &&
        !authData?.current?.service?.is_external)
    ? data.app
    : undefined;
{{/if}}
/**
  * Check if the user can create the {{SUB_MODULE_ENTITY_CAMELCASED_SINGULAR}}
  */
{{#if ENTITY_META.is_creatable}}
if (
  authData?.current?.app?._id &&
  authData?.current?.app?._id !== data.app
)
  throw new exceptions.UnauthorizedException(
    "You are not allowed to create this {{SUB_MODULE_ENTITY_CAMELCASED_SINGULAR}} on this app"
  );
{{/if}}

const userGranted = await userCan.createObject(this.ENTITY, data, authData);
if (!userGranted){
  throw new exceptions.UnauthorizedException(
    "You are not allowed to create this {{SUB_MODULE_ENTITY_CAMELCASED_SINGULAR}}"
  );
}

/**
  * Create data {{SUB_MODULE_ENTITY_CAMELCASED_SINGULAR}}
  */
const docObject: Partial<EntityAlias> = {
  ...data,
};

{{#if HAS_TRACKING_ID_PROPERTY}}
/**
  * Create tracking ID
  */
docObject.tracking_id = await createTrackingId(
  this.ENTITY,
  ITEM_SHORTCUTS,
  this.{{SUB_MODULE_ENTITY_CAMELCASED_SINGULAR}}Model as any
);
{{/if}}

{{#if ENTITY_META.has_slug}}
{{#ifEntityHasNameOrTitle .}}
/**
  * Create slug
  */
docObject.slug = await this._generateSlug(
  {{#if ENTITY_META.has_name}}data.name{{else}}data.title{{/if}},
  data.slug,
) as any;
{{/ifEntityHasNameOrTitle}}
{{/if}}

{{#if ENTITY_META.has_snapshots}}
/**
  * Create snapshots
  */
docObject.snapshots = await this._generateSnapshotsObject(
  docObject,
  null,
  authData
);
{{/if}}

{{#if HAS_SEARCH_META_PROPERTY}}
/**
  * Create search meta
  */
docObject.search_meta = this._generateSearchMeta(docObject, null);
{{/if}}


/**
  * Create the {{SUB_MODULE_ENTITY_CAMELCASED_SINGULAR}} on DB
  */
const doc = await this.{{SUB_MODULE_ENTITY_CAMELCASED_SINGULAR}}Model.create(docObject);

if (!doc)
  throw new exceptions.InternalServerError(
    "Failed to create the {{SUB_MODULE_ENTITY_CAMELCASED_SINGULAR}}"
  );

/**
  * Return the created {{SUB_MODULE_ENTITY_CAMELCASED_SINGULAR}}
  */
result = {
  data: mapDocumentToExposed(doc),
};
/********* END OF METHOD LOGIC *********/