const util = require('util')
import { DataTypes } from 'sequelize'

function fromSql(value) {
    return value
        .substring(1, value.length - 1)
        .split(',')
        .map((v) => parseFloat(v))
}

function toSql(value) {
    return JSON.stringify(value)
}

export class VECTOR extends DataTypes.ABSTRACT {
    dimensions: number
    key: string
    constructor(dimensions) {
        super()
        this.dimensions = dimensions
        this.key = `vector(${dimensions})`
    }

    toSql() {
        if (this.dimensions === undefined) {
            return 'VECTOR'
        }
        if (!Number.isInteger(this.dimensions)) {
            throw new Error('expected integer')
        }
        return util.format('VECTOR(%d)', this.dimensions)
    }

    _stringify(value) {
        return toSql(value)
    }

    static parse(value) {
        return fromSql(value)
    }
}
