from __future__ import annotations

import tempfile
import unittest
from pathlib import Path

from backend.app.db.history_repository import HistoryRepository


class HistoryRepositoryTest(unittest.TestCase):
    def setUp(self) -> None:
        self.temp_dir = tempfile.TemporaryDirectory()
        self.repo = HistoryRepository(str(Path(self.temp_dir.name) / 'history.db'))

    def tearDown(self) -> None:
        self.temp_dir.cleanup()

    def test_list_history_sorted_created_at_desc(self) -> None:
        self.repo.insert_entry_for_testing(
            {
                'id': 'old',
                'operation': 'mkdir',
                'status': 'completed',
                'source': None,
                'destination': None,
                'path': 'storage1/old',
                'error_code': None,
                'error_message': None,
                'created_at': '2026-03-10T10:00:00Z',
                'finished_at': '2026-03-10T10:00:00Z',
            }
        )
        self.repo.insert_entry_for_testing(
            {
                'id': 'new',
                'operation': 'move',
                'status': 'failed',
                'source': 'storage1/a.txt',
                'destination': 'storage1/b.txt',
                'path': None,
                'error_code': 'io_error',
                'error_message': 'failed',
                'created_at': '2026-03-10T10:01:00Z',
                'finished_at': '2026-03-10T10:01:01Z',
            }
        )

        items = self.repo.list_history(limit=100)

        self.assertEqual([item['id'] for item in items], ['new', 'old'])
