from __future__ import annotations

import sqlite3
import sys
import tempfile
import unittest
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[3]))

from backend.app.db.bookmark_repository import BookmarkRepository


class BookmarkRepositoryTest(unittest.TestCase):
    def setUp(self) -> None:
        self.temp_dir = tempfile.TemporaryDirectory()
        self.repo = BookmarkRepository(str(Path(self.temp_dir.name) / "bookmarks.db"))

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

    def test_duplicate_path_raises_integrity_error(self) -> None:
        self.repo.create_bookmark(path="storage1/a", label="A")
        with self.assertRaises(sqlite3.IntegrityError):
            self.repo.create_bookmark(path="storage1/a", label="Again")

    def test_list_order_created_at_desc(self) -> None:
        first = self.repo.create_bookmark(path="storage1/a", label="A")
        second = self.repo.create_bookmark(path="storage1/b", label="B")

        items = self.repo.list_bookmarks()

        self.assertEqual(items[0]["id"], second["id"])
        self.assertEqual(items[1]["id"], first["id"])


if __name__ == "__main__":
    unittest.main()
