import { getChangeStats, listChanges } from "@mandujs/core/change";
import { getRootDir } from "../../util/fs";

function reverseCopy<T>(items: readonly T[]): T[] {
  const reversed: T[] = [];
  for (let index = items.length - 1; index >= 0; index -= 1) {
    reversed.push(items[index] as T);
  }
  return reversed;
}

export async function changeList(): Promise<boolean> {
  const rootDir = getRootDir();

  console.log(`🥟 Mandu Change List\n`);

  try {
    const changes = await listChanges(rootDir);
    const stats = await getChangeStats(rootDir);

    if (changes.length === 0) {
      console.log(`📭 No change history found`);
      console.log(`\n💡 Start a new transaction: bunx mandu change begin`);
      return true;
    }

    // Stats
    console.log(`📊 Stats:`);
    console.log(`   Total records: ${stats.total}`);
    console.log(`   Active: ${stats.active} | Committed: ${stats.committed} | Rolled back: ${stats.rolledBack}`);
    console.log(`   Snapshots: ${stats.snapshotCount}\n`);

    // Recent records (newest first)
    console.log(`📜 Change history:`);

    const sortedChanges = reverseCopy(changes); // newest first

    for (const change of sortedChanges) {
      const statusIcon =
        change.status === "active"
          ? "🔄"
          : change.status === "committed"
            ? "✅"
            : "↩️";

      const date = new Date(change.createdAt).toLocaleString();

      console.log(`   ${statusIcon} ${change.id}`);
      console.log(`      Status: ${change.status}`);
      console.log(`      Time: ${date}`);
      if (change.message) {
        console.log(`      Message: ${change.message}`);
      }
      if (change.autoGenerated) {
        console.log(`      Source: Auto-correct`);
      }
      console.log("");
    }

    return true;
  } catch (error) {
    console.error(`❌ Failed to list history: ${error instanceof Error ? error.message : String(error)}`);
    return false;
  }
}
