import os
from io import StringIO
from django.core.management import call_command
from django.test import TestCase
from backend.core.models import DocumentTemplate


class DocumentTemplateImportCommandTest(TestCase):
    def setUp(self):
        self.yaml_content = """
        - segment_type: "title"
          content: "Document Title"
        - segment_type: "subtitle"
          content: "Document Subtitle"
        """
        self.yaml_file = 'test_template.yaml'
        with open(self.yaml_file, 'w') as f:
            f.write(self.yaml_content)

    def tearDown(self):
        if os.path.exists(self.yaml_file):
            os.remove(self.yaml_file)

    def test_import_template(self):
        out = StringIO()
        call_command('import_template', self.yaml_file, stdout=out)

        self.assertIn("Template imported successfully", out.getvalue())

        template = DocumentTemplate.objects.get(name="Default Template")
        self.assertEqual(template.content.strip(), self.yaml_content.strip())
