const db = require('../database/database');

const DRY_RUN = process.argv.includes('--dry-run');

async function migrate() {
  console.log(`🔧 migrateContractPaths start (dryRun=${DRY_RUN})`);

  // Only pick contract paths missing /contract or /gdpr segment
  const rows = await db.execute(
    `SELECT id, object_storage_id, contract_type
     FROM user_documents
     WHERE object_storage_id LIKE 'contracts/%/%/%'
       AND object_storage_id NOT LIKE '%/contract/%'
       AND object_storage_id NOT LIKE '%/gdpr/%'`
  );

  if (!rows || rows.length === 0) {
    console.log('✅ No rows to update.');
    return;
  }

  let updated = 0;
  let skipped = 0;

  for (const row of rows) {
    const key = String(row.object_storage_id || '');
    const match = key.match(/^(contracts\/(personal|company)\/\d+)\/([^/]+)$/i);
    if (!match) {
      skipped++;
      continue;
    }

    const prefix = match[1];
    const filename = match[3];
    const nextKey = `${prefix}/contract/${filename}`;

    if (DRY_RUN) {
      console.log(`DRY_RUN: ${row.id} ${key} -> ${nextKey}`);
      updated++;
      continue;
    }

    await db.execute(
      `UPDATE user_documents SET object_storage_id = ? WHERE id = ?`,
      [nextKey, row.id]
    );
    updated++;
  }

  console.log(`✅ Done. updated=${updated}, skipped=${skipped}`);
}

migrate()
  .catch(err => {
    console.error('💥 migrateContractPaths error:', err);
    process.exitCode = 1;
  })
  .finally(async () => {
    try {
      await db.close();
    } catch (_) {}
  });
