"""
Tests for SyncService
Phase 6: Site Integration & Multi-Destination Publishing
"""
from django.test import TestCase
from django.utils import timezone
from unittest.mock import patch, Mock

from igny8_core.auth.models import Account, Site, Sector, User, Plan, Industry, IndustrySector
from igny8_core.business.integration.models import SiteIntegration
from igny8_core.business.integration.services.sync_service import SyncService


class SyncServiceTestCase(TestCase):
    """Test cases for SyncService"""
    
    def setUp(self):
        """Set up test data"""
        # Create plan first
        self.plan = Plan.objects.create(
            name="Test Plan",
            slug="test-plan",
            price=0,
            credits_per_month=1000
        )
        
        # Create user first (Account needs owner)
        self.user = User.objects.create_user(
            username='testuser',
            email='test@test.com',
            password='testpass123',
            role='owner'
        )
        
        # Create account with owner
        self.account = Account.objects.create(
            name="Test Account",
            slug="test-account",
            plan=self.plan,
            owner=self.user
        )
        
        # Update user to have account
        self.user.account = self.account
        self.user.save()
        
        # Create industry and sector
        self.industry = Industry.objects.create(
            name="Test Industry",
            slug="test-industry"
        )
        
        self.industry_sector = IndustrySector.objects.create(
            industry=self.industry,
            name="Test Sector",
            slug="test-sector"
        )
        
        self.site = Site.objects.create(
            account=self.account,
            name="Test Site",
            slug="test-site",
            industry=self.industry
        )
        self.sector = Sector.objects.create(
            account=self.account,
            site=self.site,
            industry_sector=self.industry_sector,
            name="Test Sector",
            slug="test-sector"
        )
        self.integration = SiteIntegration.objects.create(
            account=self.account,
            site=self.site,
            platform='wordpress',
            platform_type='cms',
            sync_enabled=True,
            sync_status='pending'
        )
        self.service = SyncService()
    
    def test_sync_updates_status(self):
        """Test: Two-way sync functions properly"""
        with patch.object(self.service, '_sync_to_external') as mock_sync_to, \
             patch.object(self.service, '_sync_from_external') as mock_sync_from:
            mock_sync_to.return_value = {'success': True, 'synced': 5}
            mock_sync_from.return_value = {'success': True, 'synced': 3}
            
            result = self.service.sync(self.integration, direction='both')
            
            self.assertTrue(result.get('success'))
            self.integration.refresh_from_db()
            self.assertEqual(self.integration.sync_status, 'success')
            self.assertIsNotNone(self.integration.last_sync_at)
    
    def test_sync_to_external_only(self):
        """Test: Two-way sync functions properly"""
        with patch.object(self.service, '_sync_to_external') as mock_sync_to:
            mock_sync_to.return_value = {'success': True, 'synced': 5}
            
            result = self.service.sync(self.integration, direction='to_external')
            
            self.assertTrue(result.get('success'))
            mock_sync_to.assert_called_once()
    
    def test_sync_from_external_only(self):
        """Test: WordPress sync works (when plugin connected)"""
        with patch.object(self.service, '_sync_from_external') as mock_sync_from:
            mock_sync_from.return_value = {'success': True, 'synced': 3}
            
            result = self.service.sync(self.integration, direction='from_external')
            
            self.assertTrue(result.get('success'))
            mock_sync_from.assert_called_once()
    
    def test_sync_handles_errors(self):
        """Test: Two-way sync functions properly"""
        with patch.object(self.service, '_sync_to_external') as mock_sync_to:
            mock_sync_to.side_effect = Exception("Sync failed")
            
            result = self.service.sync(self.integration, direction='to_external')
            
            self.assertFalse(result.get('success'))
            self.integration.refresh_from_db()
            self.assertEqual(self.integration.sync_status, 'failed')
            self.assertIsNotNone(self.integration.sync_error)

