'use strict';

// Helper function to safely add a column if it doesn't exist
async function addColumnIfNotExists(queryInterface, tableName, columnName, columnDefinition) {
  const tableDescription = await queryInterface.describeTable(tableName);
  if (!tableDescription[columnName]) {
    await queryInterface.addColumn(tableName, columnName, columnDefinition);
  }
}

module.exports = {
  async up(queryInterface, Sequelize) {
    // Add filename column to wda table to store the custom/original filename
    await addColumnIfNotExists(queryInterface, 'wda', 'filename', {
      type: Sequelize.STRING,
      allowNull: true,
      comment: 'Original or custom filename provided by user (for display purposes)',
    });

    // For existing records, populate filename from filepath
    // Get all WDA records and update them
    const [wdaRecords] = await queryInterface.sequelize.query(`
      SELECT id, filepath FROM wda WHERE filename IS NULL;
    `);

    // Update each record with the filename extracted from filepath
    for (const record of wdaRecords) {
      const pathParts = record.filepath.split('/');
      const filename = pathParts[pathParts.length - 1];
      await queryInterface.sequelize.query(
        `
        UPDATE wda SET filename = :filename WHERE id = :id;
      `,
        {
          replacements: { filename, id: record.id },
        }
      );
    }
  },

  async down(queryInterface, Sequelize) {
    await queryInterface.removeColumn('wda', 'filename');
  },
};
