import json
import shutil
import tempfile
import unittest
import guayaba as guba
from pathlib import Path


@guba.dataclass("/hello/{id}")
class User:
    id: int
    name: str
    tags: list[str]


class TestSave(unittest.TestCase):
    def setUp(self):
        output = tempfile.mkdtemp()
        guba.get_app(output)
        self.output = Path(output)

    def tearDown(self):
        shutil.rmtree(self.output)

    def test_save(self):
        user = User(id=1, name="Alice", tags=["tag1", "tag2"])
        guba.save(user, "user_1.json")

        saved_file = self.output / "user_1.json"

        self.assertTrue(saved_file.exists(), "Expected save() to create the output file")

        with open(saved_file, "r", encoding="utf-8") as f:
            content = json.load(f)

        self.assertEqual(
            content,
            {"id": 1, "name": "Alice", "tags": ["tag1", "tag2"]},
            "Saved JSON content does not match the model data",
        )

    def test_load(self):
        saved_file = self.output / "user_1.json"
        saved_file.write_text(
            json.dumps({"id": 1, "name": "Alice", "tags": ["tag1", "tag2"]}),
            encoding="utf-8",
        )

        loaded_user = guba.load(str(saved_file), User)

        self.assertIsInstance(loaded_user, User)
        self.assertEqual(loaded_user.id, 1)
        self.assertEqual(loaded_user.name, "Alice")
        self.assertEqual(loaded_user.tags, ["tag1", "tag2"])

