from django.test import TestCase, override_settings
from unittest.mock import patch

from business import tasks


@override_settings(
    CELERY_TASK_ALWAYS_EAGER=True,
    CELERY_TASK_EAGER_PROPAGATES=True,
)
class PurchaseOrderStockTaskTestCase(TestCase):
    def setUp(self):
        self.purchase_order_id = 123
        self.warehouse_id = 456
        self.items = [{'product_id': 1, 'quantities': ['5']}]

    def test_task_delegates_to_service(self):
        with patch('business.tasks.business_services.create_purchase_order_stock_entries_sync') as mock_sync:
            mock_sync.return_value = {'purchase_order_id': self.purchase_order_id}

            async_result = tasks.create_purchase_order_stock_entries.delay(
                purchase_order_id=self.purchase_order_id,
                warehouse_id=self.warehouse_id,
                items=self.items,
                created_by_id=999,
            )
            payload = async_result.get(timeout=5)

        mock_sync.assert_called_once_with(
            purchase_order_id=self.purchase_order_id,
            warehouse_id=self.warehouse_id,
            items=self.items,
            created_by_id=999,
        )
        self.assertEqual(payload['purchase_order_id'], self.purchase_order_id)
        self.assertIn('task_id', payload)


@override_settings(
    CELERY_TASK_ALWAYS_EAGER=True,
    CELERY_TASK_EAGER_PROPAGATES=True,
)
class SalesOrderStockTaskTestCase(TestCase):
    def setUp(self):
        self.sales_order_id = 321
        self.warehouse_id = 654
        self.items = [{'product_id': 2, 'quantities': ['4']}]

    def test_task_delegates_to_service(self):
        with patch('business.tasks.business_services.create_sales_order_stock_entries_sync') as mock_sync:
            mock_sync.return_value = {'sales_order_id': self.sales_order_id}

            async_result = tasks.create_sales_order_stock_entries.delay(
                sales_order_id=self.sales_order_id,
                warehouse_id=self.warehouse_id,
                items=self.items,
                created_by_id=777,
            )
            payload = async_result.get(timeout=5)

        mock_sync.assert_called_once_with(
            sales_order_id=self.sales_order_id,
            warehouse_id=self.warehouse_id,
            items=self.items,
            created_by_id=777,
        )
        self.assertEqual(payload['sales_order_id'], self.sales_order_id)
        self.assertIn('task_id', payload)
