import { QueryInterface, DataTypes } from 'sequelize';

/**
 * Helper function to check if a column exists in a table
 */
async function columnExists(
    queryInterface: QueryInterface,
    tableName: string,
    columnName: string
): Promise<boolean> {
    try {
        const tableDescription = await queryInterface.describeTable(tableName);
        return columnName in tableDescription;
    } catch (error) {
        return false;
    }
}

export async function up(queryInterface: QueryInterface): Promise<void> {
    const tableName = 'claim_invoices';
    
    // Add wfm_push_status
    if (!(await columnExists(queryInterface, tableName, 'wfm_push_status'))) {
        await queryInterface.addColumn(tableName, 'wfm_push_status', {
            type: DataTypes.STRING(20),
            allowNull: true,
            defaultValue: 'PENDING'
        });
    }

    // Add wfm_push_error
    if (!(await columnExists(queryInterface, tableName, 'wfm_push_error'))) {
        await queryInterface.addColumn(tableName, 'wfm_push_error', {
            type: DataTypes.TEXT,
            allowNull: true
        });
    }
}

export async function down(queryInterface: QueryInterface): Promise<void> {
    const tableName = 'claim_invoices';
    
    if (await columnExists(queryInterface, tableName, 'wfm_push_status')) {
        await queryInterface.removeColumn(tableName, 'wfm_push_status');
    }

    if (await columnExists(queryInterface, tableName, 'wfm_push_error')) {
        await queryInterface.removeColumn(tableName, 'wfm_push_error');
    }
}
