// Lightweight Knex migration runner.
// Wraps knex.migrate.latest() with logging and a final cleanup so the
// caller (server/src/database/init.js) doesn't have to manage the
// connection lifecycle.

const path = require('path');
const knex = require('knex');
const knexConfig = require('../../../knexfile');

async function runMigrations() {
  const k = knex(knexConfig);
  try {
    const [batch, log] = await k.migrate.latest();
    if (log.length === 0) {
      console.log('[migrate] already up to date (no new migrations)');
    } else {
      console.log(`[migrate] batch ${batch} applied ${log.length} migration(s):`);
      for (const m of log) console.log(`  - ${m}`);
    }
    return { batch, applied: log };
  } finally {
    await k.destroy();
  }
}

async function rollbackMigrations() {
  const k = knex(knexConfig);
  try {
    const [batch, log] = await k.migrate.rollback();
    console.log(`[migrate] rolled back batch ${batch} (${log.length} migration(s))`);
    return { batch, rolled: log };
  } finally {
    await k.destroy();
  }
}

async function migrationStatus() {
  const k = knex(knexConfig);
  try {
    const list = await k.migrate.status();
    // Returns a richer status object including completed + pending
    const completed = list.filter(s => s.applied).length;
    const pending = list.length - completed;
    console.log(`[migrate] status: ${completed} applied, ${pending} pending`);
    for (const s of list) {
      console.log(`  ${s.applied ? '✓' : '·'} ${s.name}`);
    }
    return { completed, pending, list };
  } finally {
    await k.destroy();
  }
}

module.exports = { runMigrations, rollbackMigrations, migrationStatus };
