// SPDX-FileCopyrightText: 2026 FocusFlow contributors
// SPDX-License-Identifier: AGPL-3.0-only

/// Tests Encrypted Backup behavior for the Scheduler Backup package.
library;

import 'dart:convert';
import 'dart:io';

import 'package:scheduler_backup/backup.dart';
import 'package:test/test.dart';

/// Entry point for this executable Dart file.
/// It wires the local command, test, or application behavior needed by this repository without exposing additional public API.
void main() {
  test('encrypted backup round trips a SQLite file using temp paths', () async {
    final temp =
        await Directory.systemTemp.createTemp('scheduler-backup-test-');
    addTearDown(() => temp.delete(recursive: true));
    final sqlite =
        File('${temp.path}${Platform.pathSeparator}scheduler.sqlite');
    final backupDirectory =
        Directory('${temp.path}${Platform.pathSeparator}backups');
    final restored =
        File('${temp.path}${Platform.pathSeparator}restored.sqlite');
    const sqliteBytes = <int>[
      0x53,
      0x51,
      0x4c,
      0x69,
      0x74,
      0x65,
      0x20,
      0x66,
      0x6f,
      0x72,
      0x6d,
      0x61,
      0x74,
      0x20,
      0x33,
      0x00,
      0x01,
      0x02,
      0x03,
    ];
    await sqlite.writeAsBytes(sqliteBytes);

    final backup = await createEncryptedBackup(
      passphrase: 'correct horse battery staple',
      sqliteFile: sqlite,
      backupDirectory: backupDirectory,
      now: DateTime(2026, 6, 26, 9, 7),
    );

    expect(backup.path, endsWith('20260626_0907.db.enc'));
    expect(await backup.exists(), isTrue);
    expect(await backup.readAsBytes(), isNot(sqliteBytes));
    final envelope =
        jsonDecode(await backup.readAsString()) as Map<String, Object?>;
    expect(envelope['cipher'], 'aes-256-gcm');

    await restoreEncryptedBackup(
      backup,
      'correct horse battery staple',
      targetFile: restored,
    );

    expect(await restored.readAsBytes(), sqliteBytes);
  });

  test('wrong passphrase throws BackupDecryptionException', () async {
    final temp =
        await Directory.systemTemp.createTemp('scheduler-backup-test-');
    addTearDown(() => temp.delete(recursive: true));
    final sqlite =
        File('${temp.path}${Platform.pathSeparator}scheduler.sqlite');
    await sqlite.writeAsBytes(utf8.encode('sqlite bytes'));
    final backup = await createEncryptedBackup(
      passphrase: 'right-passphrase',
      sqliteFile: sqlite,
      backupDirectory: temp,
      now: DateTime(2026, 6, 26, 9, 7),
    );

    expect(
      () => restoreEncryptedBackup(
        backup,
        'wrong-passphrase',
        targetFile: File('${temp.path}${Platform.pathSeparator}restore.sqlite'),
      ),
      throwsA(isA<BackupDecryptionException>()),
    );
  });
}
