import mysql from 'mysql2/promise';
import dotenv from 'dotenv';

dotenv.config();

const report = [];

const dbConfig = {
  host: process.env.DB_HOST || 'localhost',
  user: process.env.DB_USER || 'root',
  password: process.env.DB_PASSWORD || '',
  database: process.env.DB_NAME || 'trainingdiary',
};

async function getIndexSummary(connection, table) {
  const [rows] = await connection.execute(`SHOW INDEX FROM \`${table}\``);
  const summary = rows.reduce((acc, r) => {
    const key = r.Key_name;
    acc[key] = acc[key] || { unique: r.Non_unique === 0, columns: [] };
    acc[key].columns.push(r.Column_name);
    return acc;
  }, {});
  return summary;
}

async function cleanupUserTokenKeys() {
  let connection;
  const table = 'UserToken';

  try {
    report.push(`Connecting to DB: ${JSON.stringify(dbConfig)}`);
    connection = await mysql.createConnection(dbConfig);

    report.push('');
    report.push(`Before cleanup (indexes on ${table}):`);
    let before = await getIndexSummary(connection, table);
    Object.entries(before).forEach(([name, info]) => {
      report.push(`  - ${name} ${info.unique ? '(UNIQUE)' : ''} -> [${info.columns.join(', ')}]`);
    });

    // Drop all non-PRIMARY indexes on UserToken
    const [indexes] = await connection.execute(`SHOW INDEX FROM \`${table}\``);
    const keyNames = Array.from(new Set(indexes.map(i => i.Key_name))).filter(k => k !== 'PRIMARY');

    for (const keyName of keyNames) {
      try {
        await connection.execute(`DROP INDEX \`${keyName}\` ON \`${table}\``);
        report.push(`Dropped index: ${keyName}`);
      } catch (err) {
        report.push(`Could not drop ${keyName}: ${err.code || err.message}`);
      }
    }

    // Re-create minimal, deterministic indexes
    // Unique on token (column is 'token')
    try {
      await connection.execute(`CREATE UNIQUE INDEX \`uniq_UserToken_token\` ON \`${table}\` (\`token\`)`);
      report.push('Created UNIQUE index: uniq_UserToken_token (token)');
    } catch (err) {
      report.push(`Could not create uniq_UserToken_token: ${err.code || err.message}`);
    }

    // Helpful index on user_id if column exists
    try {
      const [cols] = await connection.execute(`SHOW COLUMNS FROM \`${table}\` LIKE 'user_id'`);
      if (cols && cols.length > 0) {
        await connection.execute(`CREATE INDEX \`idx_UserToken_user_id\` ON \`${table}\` (\`user_id\`)`);
        report.push('Created INDEX: idx_UserToken_user_id (user_id)');
      } else {
        report.push('Column user_id not found, skip creating idx_UserToken_user_id');
      }
    } catch (err) {
      report.push(`Could not create idx_UserToken_user_id: ${err.code || err.message}`);
    }

    report.push('');
    report.push(`After cleanup (indexes on ${table}):`);
    const after = await getIndexSummary(connection, table);
    Object.entries(after).forEach(([name, info]) => {
      report.push(`  - ${name} ${info.unique ? '(UNIQUE)' : ''} -> [${info.columns.join(', ')}]`);
    });

    report.push('');
    report.push('Done.');
  } catch (err) {
    console.error('Cleanup failed:', err);
    process.exitCode = 1;
  } finally {
    if (connection) await connection.end();
    if (report.length > 0) {
      process.stdout.write(`${report.join('\n')}\n`);
    }
  }
}

cleanupUserTokenKeys();


