
import { QueryInterface, DataTypes } from 'sequelize';

export async function up(queryInterface: QueryInterface): Promise<void> {
    await queryInterface.createTable('api_tokens', {
        id: {
            type: DataTypes.UUID,
            defaultValue: DataTypes.UUIDV4,
            primaryKey: true,
            allowNull: false,
        },
        user_id: {
            type: DataTypes.UUID,
            allowNull: false,
            references: {
                model: 'users',
                key: 'user_id',
            },
            onUpdate: 'CASCADE',
            onDelete: 'CASCADE',
        },
        name: {
            type: DataTypes.STRING(100),
            allowNull: false,
            comment: 'User-friendly name for the token',
        },
        prefix: {
            type: DataTypes.STRING(10),
            allowNull: false,
            comment: 'First few characters of token for identification (e.g., re_1234)',
        },
        token_hash: {
            type: DataTypes.STRING,
            allowNull: false,
            comment: 'Bcrypt hash of the full token',
        },
        last_used_at: {
            type: DataTypes.DATE,
            allowNull: true,
        },
        expires_at: {
            type: DataTypes.DATE,
            allowNull: true,
            comment: 'Optional expiration date',
        },
        is_active: {
            type: DataTypes.BOOLEAN,
            defaultValue: true,
            allowNull: false,
        },
        created_at: {
            type: DataTypes.DATE,
            allowNull: false,
            defaultValue: DataTypes.NOW,
        },
        updated_at: {
            type: DataTypes.DATE,
            allowNull: false,
            defaultValue: DataTypes.NOW,
        },
    });

    // Indexes
    await queryInterface.addIndex('api_tokens', ['user_id']);
    await queryInterface.addIndex('api_tokens', ['prefix']);
}

export async function down(queryInterface: QueryInterface): Promise<void> {
    await queryInterface.dropTable('api_tokens');
}
