import * as _ from 'lodash-es';
import { databaseTypes, fieldTypes } from '../../../jdl/jhipster/index.mjs';
const { MYSQL, MARIADB } = databaseTypes;
const { CommonDBTypes, RelationalOnlyDBTypes, BlobTypes } = fieldTypes;
const { STRING, INTEGER, LONG, BIG_DECIMAL, FLOAT, DOUBLE, UUID, BOOLEAN, LOCAL_DATE, ZONED_DATE_TIME, INSTANT, DURATION } = CommonDBTypes;
const { BYTES } = RelationalOnlyDBTypes;
const { TEXT } = BlobTypes;
function parseLiquibaseColumnType(entity, field) {
    const fieldType = field.fieldType;
    if (fieldType === STRING || field.fieldIsEnum) {
        return `varchar(${field.fieldValidateRulesMaxlength || 255})`;
    }
    if (fieldType === INTEGER) {
        return 'integer';
    }
    if (fieldType === LONG) {
        return 'bigint';
    }
    if (fieldType === FLOAT) {
        return '${floatType}';
    }
    if (fieldType === DOUBLE) {
        return 'double';
    }
    if (fieldType === BIG_DECIMAL) {
        return 'decimal(21,2)';
    }
    if (fieldType === LOCAL_DATE) {
        return 'date';
    }
    if (fieldType === INSTANT) {
        return '${datetimeType}';
    }
    if (fieldType === ZONED_DATE_TIME) {
        return '${datetimeType}';
    }
    if (fieldType === DURATION) {
        return 'bigint';
    }
    if (fieldType === UUID) {
        return '${uuidType}';
    }
    if (fieldType === BYTES && field.fieldTypeBlobContent !== TEXT) {
        return '${blobType}';
    }
    if (field.fieldTypeBlobContent === TEXT) {
        return '${clobType}';
    }
    if (fieldType === BOOLEAN) {
        return 'boolean';
    }
    return undefined;
}
function parseLiquibaseLoadColumnType(entity, field) {
    const columnType = field.columnType;
    if (['integer', 'bigint', 'double', 'decimal(21,2)', '${floatType}'].includes(columnType)) {
        return 'numeric';
    }
    if (field.fieldIsEnum) {
        return 'string';
    }
    if (['date', '${datetimeType}'].includes(columnType)) {
        return 'date';
    }
    if (columnType === 'boolean') {
        return columnType;
    }
    if (columnType === '${blobType}') {
        return 'blob';
    }
    if (columnType === '${clobType}') {
        return 'clob';
    }
    const { prodDatabaseType } = entity;
    if (columnType === '${uuidType}' &&
        prodDatabaseType !== MYSQL &&
        prodDatabaseType !== MARIADB) {
        return '${uuidType}';
    }
    return 'string';
}
export default function prepareField(entity, field) {
    _.defaults(field, {
        columnType: parseLiquibaseColumnType(entity, field),
        shouldDropDefaultValue: field.fieldType === ZONED_DATE_TIME || field.fieldType === INSTANT,
        shouldCreateContentType: field.fieldType === BYTES && field.fieldTypeBlobContent !== TEXT,
        nullable: !(field.fieldValidate === true && field.fieldValidateRules.includes('required')),
    });
    _.defaults(field, {
        loadColumnType: parseLiquibaseLoadColumnType(entity, field),
    });
    return field;
}
