import json
from datetime import datetime, timezone

import pytest

from app.services import db_backup


def test_list_database_backups_reads_metadata(tmp_path, monkeypatch):
    backup = tmp_path / "certificate_system_20260623_120000.sqlite3"
    backup.write_bytes(b"sqlite-data")
    metadata = {
        "filename": backup.name,
        "database_type": "sqlite",
        "created_at": datetime(2026, 6, 23, 12, 0, tzinfo=timezone.utc).isoformat(),
        "reason": "manual",
    }
    backup.with_name(f"{backup.name}.json").write_text(json.dumps(metadata), encoding="utf-8")
    monkeypatch.setattr(db_backup, "_backup_dir", lambda: tmp_path)

    items = db_backup.list_database_backups()

    assert items[0]["filename"] == backup.name
    assert items[0]["database_type"] == "sqlite"
    assert items[0]["reason"] == "manual"
    assert items[0]["size_label"] == "11 B"


def test_resolve_backup_path_rejects_path_traversal(tmp_path, monkeypatch):
    monkeypatch.setattr(db_backup, "_backup_dir", lambda: tmp_path)

    with pytest.raises(db_backup.BackupError):
        db_backup._resolve_backup_path("../certificate_system_20260623_120000.sqlite3")


def test_backup_target_does_not_overwrite_existing_file(tmp_path, monkeypatch):
    created_at = datetime(2026, 6, 23, 12, 0, tzinfo=timezone.utc)
    existing = tmp_path / "certificate_system_20260623_120000.sqlite3"
    existing.write_bytes(b"old")
    monkeypatch.setattr(db_backup, "_backup_dir", lambda: tmp_path)

    target = db_backup._backup_target("sqlite", "manual", created_at)

    assert target.name == "certificate_system_20260623_120000_2.sqlite3"


def test_restore_requires_exact_confirmation(tmp_path, monkeypatch):
    backup = tmp_path / "certificate_system_20260623_120000.sqlite3"
    backup.write_bytes(b"sqlite-data")
    monkeypatch.setattr(db_backup, "_backup_dir", lambda: tmp_path)

    with pytest.raises(db_backup.BackupError, match="确认文本不正确"):
        db_backup.restore_database_backup(backup.name, "RESTORE wrong-file")
