import _ from 'lodash';
import { AKAPIException } from '../../exceptions/api_exception.js';
import { PG_CODE_UNIQUENESS_VIOLATION } from '../../exceptions/http_exception_handler.js';
export const AKModelServiceCreate = (superclass) => {
    return class extends superclass {
        static createUniquenessViolationException = AKAPIException.alreadyExist;
        async preCreate(_payload) { }
        async create(payload) {
            await this.preCreate(payload);
            for (const relation of this.model.$relationsDefinitions.values()) {
                if (relation.type === 'belongsTo')
                    if (_.has(payload, relation.relationName)) {
                        relation.boot();
                        const localKeyValue = _.get(payload, [relation.relationName, relation.localKey]);
                        _.set(payload, relation.foreignKeyColumnName, localKeyValue);
                    }
            }
            let created;
            try {
                created = await this.model.create(payload);
            }
            catch (e) {
                if (e.code === PG_CODE_UNIQUENESS_VIOLATION) {
                    throw this.constructor.createUniquenessViolationException;
                }
                else
                    throw e;
            }
            await this.updateRelations(created, payload);
            const fetchedCreated = (await this.findBy(this.model.primaryKey, created[this.model.primaryKey]));
            return await this.postCreate(payload, fetchedCreated);
        }
        async postCreate(_payload, created) {
            return created;
        }
        async findOrCreate(payload) {
            const pk = this.model.primaryKey;
            const pkValue = !_.isEmpty(payload) ? payload[pk] : undefined;
            if (!pkValue)
                return await this.create(payload);
            return (await this.findBy(pk, payload[pk])) || (await this.create(payload));
        }
    };
};
//# sourceMappingURL=create.js.map