import {sequelize} from "../app";
import * as crypto from "crypto";
import {DataTypes, InferAttributes, InferCreationAttributes, Model} from "sequelize";

export enum TokenType {
    API, SESSION
}

export interface IToken extends Model<InferAttributes<IToken>, InferCreationAttributes<IToken>> {
    token?: string
    clientId: number
    type?: TokenType
    userAgent?: string
    created?: Date
}

const TokenSchema = sequelize.define<IToken>('tokens', {
    token: {
        type: DataTypes.STRING,
        defaultValue: () => crypto.randomBytes(48).toString('hex'),
        primaryKey: true
    },
    clientId: {
        type: DataTypes.BIGINT,
        allowNull: false
    },
    type: {
        type: DataTypes.STRING,
        defaultValue: TokenType.API
    },
    userAgent: {
        type: DataTypes.STRING,
        allowNull: true
    },
    created: {
        type: DataTypes.DATE,
        defaultValue: Date.now
    }
});

export const Token = TokenSchema;