import { describe, expect, it } from 'vitest';
import { buildHistoryRecord } from '../efcore-history.js';

const baseInput = {
  timestamp: '2026-06-02T10:00:00.000Z',
  cwd: 'D:/projets/app',
  currentBranch: 'release/3.55.0',
  baseBranch: 'origin/main',
  branchType: 'release',
  confirmed: true,
  assemblies: [
    {
      assemblyName: 'App',
      deletedMigrations: ['core_v3_54_0_001_InitialCreate.cs', 'core_v3_54_0_002_AddInvoices.cs'],
      parentMigrationsDestroyed: ['core_v3_54_0_001_InitialCreate', 'core_v3_54_0_002_AddInvoices'],
      newMigrationName: 'core_v3_55_0_001_InitialCreate',
      backupDir: '.efcore-squash-backup/2026-06-02T10-00-00/App',
    },
  ],
};

describe('buildHistoryRecord', () => {
  it('marks a brute-force run as operation "squash-bruteforce"', () => {
    const r = buildHistoryRecord({ ...baseInput, bruteForce: true });
    expect(r.operation).toBe('squash-bruteforce');
    expect(r.bruteForce).toBe(true);
    expect(r.confirmed).toBe(true);
    expect(r.assemblies[0].parentMigrationsDestroyed).toHaveLength(2);
  });

  it('marks a normal destructive squash as operation "squash"', () => {
    const r = buildHistoryRecord({
      ...baseInput,
      bruteForce: false,
      assemblies: [
        {
          assemblyName: 'App',
          deletedMigrations: ['core_v3_54_0_003_BranchOnly.cs'],
          parentMigrationsDestroyed: [], // a normal squash never touches reference migrations
          newMigrationName: 'core_v3_54_0_003_Consolidated',
          backupDir: '.efcore-squash-backup/x/App',
        },
      ],
    });
    expect(r.operation).toBe('squash');
    expect(r.bruteForce).toBe(false);
    expect(r.assemblies[0].parentMigrationsDestroyed).toEqual([]);
  });

  it('labels a rebase-snapshot run as operation "rebase-snapshot"', () => {
    const r = buildHistoryRecord({ ...baseInput, bruteForce: false, rebaseSnapshot: true });
    expect(r.operation).toBe('rebase-snapshot');
  });

  it('bruteForce wins over rebaseSnapshot for the operation label', () => {
    const r = buildHistoryRecord({ ...baseInput, bruteForce: true, rebaseSnapshot: true });
    expect(r.operation).toBe('squash-bruteforce');
  });

  it('passes the injected timestamp + context through verbatim', () => {
    const r = buildHistoryRecord({ ...baseInput, bruteForce: true });
    expect(r.timestamp).toBe('2026-06-02T10:00:00.000Z');
    expect(r.currentBranch).toBe('release/3.55.0');
    expect(r.baseBranch).toBe('origin/main');
    expect(r.branchType).toBe('release');
    expect(r.cwd).toBe('D:/projets/app');
  });

  it('round-trips through JSON (record is serializable)', () => {
    const r = buildHistoryRecord({ ...baseInput, bruteForce: true });
    expect(JSON.parse(JSON.stringify(r))).toEqual(r);
  });
});
