const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');

const dbPath = path.join(os.tmpdir(), `bill-tracker-csv-import-test-${process.pid}.sqlite`);
process.env.DB_PATH = dbPath;

const { getDb, closeDb } = require('../db/database');
const {
  commitCsvTransactions,
  previewCsvTransactions,
} = require('../services/csvTransactionImportService');

function createUser(db) {
  return db.prepare(`
    INSERT INTO users (username, password_hash, role, active, email, created_at, updated_at)
    VALUES ('csv-test-user', 'x', 'user', 1, 'csv-test-user@local', datetime('now'), datetime('now'))
  `).run().lastInsertRowid;
}

test.after(() => {
  closeDb();
  for (const suffix of ['', '-wal', '-shm']) {
    fs.rmSync(`${dbPath}${suffix}`, { force: true });
  }
});

test('CSV transaction import previews, commits, and skips duplicate row hashes', () => {
  const db = getDb();
  const userId = createUser(db);
  const csv = Buffer.from([
    'Date,Description,Amount,Account',
    '2026-05-16,Water Bill,-85.00,Checking',
    '2026-05-17,Paycheck,1200.50,Checking',
    '',
  ].join('\n'));

  const preview = previewCsvTransactions(userId, csv, { original_filename: 'bank.csv' });

  assert.deepEqual(preview.suggestedMapping, {
    posted_date: 'Date',
    description: 'Description',
    amount: 'Amount',
    account: 'Account',
  });
  assert.equal(preview.rowCount, 2);
  assert.equal(preview.sampleRows.length, 2);

  const first = commitCsvTransactions(userId, preview.import_session_id, preview.suggestedMapping);

  assert.equal(first.imported, 2);
  assert.equal(first.skipped, 0);
  assert.equal(first.failed, 0);
  assert.deepEqual(
    db.prepare('SELECT amount, source_type FROM transactions WHERE user_id = ? ORDER BY id').all(userId),
    [
      { amount: -8500, source_type: 'file_import' },
      { amount: 120050, source_type: 'file_import' },
    ],
  );

  const duplicatePreview = previewCsvTransactions(userId, csv, { original_filename: 'bank.csv' });
  const duplicate = commitCsvTransactions(userId, duplicatePreview.import_session_id, duplicatePreview.suggestedMapping);

  assert.equal(duplicate.imported, 0);
  assert.equal(duplicate.skipped, 2);
  assert.equal(duplicate.failed, 0);
});

