import {Logger} from '@nestjs/common';

import {getAttributes, getOptions} from './decorator.utils';

export function loadModel(connection: any, entity: any): Promise<any> {
    const model = connection.loadSchema(entity.name || entity.table_name, getSchema(entity) as any);
    return new Promise((resolve) => {
        model.syncDB((err) => {
            if (err) {
                Logger.error(err.message, err.stack, 'ScyllaModule');
                return resolve(model);
            }
            return resolve(model);
        });
    });
}

export function getSchema(entity: Function) {
    const attributes = getAttributes(entity.prototype) || {};
    const {instanceMethods, classMethods, ...options} = getOptions(entity.prototype) || {};
    return {...options, fields: {...attributes}};
}
