import os
import csv
import tempfile
from django.core.management import call_command
from django.test import TestCase
from backend.core.models import Risk

class ImportRisksCommandTest(TestCase):
    
    def setUp(self):
        """Create a temporary CSV file with test risk data"""
        self.temp_csv = tempfile.NamedTemporaryFile(mode="w", delete=False, newline='', encoding='utf-8')
        fieldnames = [
            "Risk ID", "Category", "Risk Name", "Primary Impact",
            "Secondary Impact", "Tertiary Impact", "Detection Difficulty",
            "Recovery Complexity", "Business Impact Severity"
        ]
        
        writer = csv.DictWriter(self.temp_csv, fieldnames=fieldnames)
        writer.writeheader()
        writer.writerow({
            "Risk ID": "1",
            "Category": "Operational",
            "Risk Name": "Data Loss",
            "Primary Impact": "High",
            "Secondary Impact": "Medium",
            "Tertiary Impact": "Low",
            "Detection Difficulty": "Hard",
            "Recovery Complexity": "Complex",
            "Business Impact Severity": "Severe"
        })
        self.temp_csv.close()

    def test_import_risks_command(self):
        """Test importing risks from a CSV file"""
        # Ensure no risks exist before import
        self.assertEqual(Risk.objects.count(), 0)
        
        # Run the import command
        call_command('import_risks', self.temp_csv.name)
        
        # Check if the risk has been imported
        self.assertEqual(Risk.objects.count(), 1)
        risk = Risk.objects.get(risk_id="1")
        self.assertEqual(risk.category, "Operational")
        self.assertEqual(risk.risk_name, "Data Loss")
        self.assertEqual(risk.primary_impact, "High")
        self.assertEqual(risk.secondary_impact, "Medium")
        self.assertEqual(risk.tretiary_impact, "Low")  # Corrected spelling
        self.assertEqual(risk.businnes_impact_severity, "Severe")  # Corrected spelling

    def tearDown(self):
        """Remove temporary CSV file after test"""
        os.remove(self.temp_csv.name)
