from decimal import Decimal

from django.contrib.auth import get_user_model
from django.test import TestCase
from django.utils import timezone
from unittest.mock import patch

from basic_info import models as basic_models
from stock import models as stock_models
from business import models as business_models, services

from .fixtures import create_basic_fixtures


class PurchaseReturnServiceTestCase(TestCase):
    def setUp(self):
        (
            self.merchant,
            self.supplier,
            self.warehouse_strict,
            self.warehouse_relaxed,
            self.product,
            self.operator,
        ) = create_basic_fixtures()
        self.warehouse_strict_out = basic_models.WareHouse.objects.create(
            merchant=self.merchant,
            name='采退严出仓',
            mode=basic_models.WareHouseModeEnum.RESTRICT_IN_OUT,
        )
        User = get_user_model()
        self.user = User.objects.create_user(username='purchase-return', password='pass123')
        self.strict_items = [
            {'product_id': self.product.id, 'numbers': [4, 2], 'price': '11.5', 'unit': '米'}
        ]
        self.strict_out_items = [
            {
                'product_id': self.product.id,
                'consume_detail_ids': [10, 11],
                'quantity': 30,
                'price': '12.0',
                'unit': '米',
            }
        ]

    def test_create_purchase_return_order_success(self):
        order = services.create_purchase_return_order(
            merchant=self.merchant,
            supplier=self.supplier,
            return_date=timezone.now().date(),
            warehouse=self.warehouse_strict,
            operator=self.operator,
            items=self.strict_items,
            created_by=self.user,
        )
        self.assertEqual(order.status, business_models.PurchaseReturnStatusEnum.PENDING)
        self.assertEqual(order.items.count(), 1)
        item = order.items.first()
        self.assertEqual(item.quantity_of_rolls, '4,2')
        self.assertEqual(item.split_quantity_of_rolls(), [4, 2])

    def test_purchase_return_order_human_id_generation(self):
        order = services.create_purchase_return_order(
            merchant=self.merchant,
            supplier=self.supplier,
            return_date=timezone.now().date(),
            warehouse=self.warehouse_strict,
            operator=self.operator,
            items=self.strict_items,
            created_by=self.user,
        )
        self.assertIsNotNone(order.human_id)
        self.assertEqual(
            order.human_id,
            f"CT{order.created_at.strftime('%Y%m%d')}{order.id:06d}",
        )

    def test_review_purchase_return_order_triggers_task_and_balance(self):
        order = services.create_purchase_return_order(
            merchant=self.merchant,
            supplier=self.supplier,
            return_date=timezone.now().date(),
            warehouse=self.warehouse_relaxed,
            operator=self.operator,
            items=[{'product_id': self.product.id, 'quantity': 40, 'num_of_rolls': 2, 'price': '10.0'}],
            created_by=self.user,
        )
        with patch('business.services.create_purchase_return_order_stock_entries.delay') as mock_delay:
            reviewed = services.review_purchase_return_order(
                purchase_return_order=order,
                target_status=business_models.PurchaseReturnStatusEnum.APPROVED,
                reviewed_by=self.user,
            )
        self.assertEqual(reviewed.status, business_models.PurchaseReturnStatusEnum.APPROVED)
        mock_delay.assert_called_once()
        balance = business_models.SupplierBalance.objects.get(
            merchant=self.merchant,
            supplier=self.supplier,
        )
        self.assertEqual(balance.balance, Decimal('-400.00'))
        record = business_models.BalanceChangeRecord.objects.get(
            merchant=self.merchant,
            source_type=business_models.BalanceChangeSourceEnum.PURCHASE_RETURN_ORDER,
            source_id=order.id,
        )
        self.assertEqual(record.direction, business_models.BalanceChangeDirectionEnum.DECREASE)

    def test_purchase_return_cancel_blocked_after_stock_created(self):
        order = services.create_purchase_return_order(
            merchant=self.merchant,
            supplier=self.supplier,
            return_date=timezone.now().date(),
            warehouse=self.warehouse_relaxed,
            operator=self.operator,
            items=[{'product_id': self.product.id, 'quantity': 20, 'num_of_rolls': 2, 'price': '9.5'}],
        )
        stock_models.StockChangeRecord.objects.create(
            merchant=self.merchant,
            type=stock_models.StockChangeTypeEnum.REMOVE,
            warehouse=self.warehouse_relaxed,
            source_type=stock_models.StockChangeSourceEnum.PURCHASE_RETURN,
            source_id=order.id,
        )
        with self.assertRaises(ValueError):
            services.review_purchase_return_order(
                purchase_return_order=order,
                target_status=business_models.PurchaseReturnStatusEnum.CANCELLED,
            )

    def test_purchase_return_strict_out_requires_consume_ids(self):
        payload = [
            {
                'product_id': self.product.id,
                'quantity': 10,
                'price': '8.5',
                'unit': '米',
            }
        ]
        with self.assertRaises(ValueError):
            services.create_purchase_return_order(
                merchant=self.merchant,
                supplier=self.supplier,
                return_date=timezone.now().date(),
                warehouse=self.warehouse_strict_out,
                operator=self.operator,
                items=payload,
            )

    def test_update_purchase_return_order_success(self):
        order = services.create_purchase_return_order(
            merchant=self.merchant,
            supplier=self.supplier,
            return_date=timezone.now().date(),
            warehouse=self.warehouse_strict,
            operator=self.operator,
            items=self.strict_items,
            created_by=self.user,
        )
        updated = services.update_purchase_return_order(
            purchase_return_order=order,
            items=self.strict_items,
            remarks='updated',
        )
        self.assertEqual(updated.remarks, 'updated')
        self.assertEqual(updated.items.count(), 1)
        self.assertEqual(updated.items.first().split_quantity_of_rolls(), [4, 2])

    def test_update_purchase_return_order_rejects_non_pending(self):
        order = services.create_purchase_return_order(
            merchant=self.merchant,
            supplier=self.supplier,
            return_date=timezone.now().date(),
            warehouse=self.warehouse_strict,
            operator=self.operator,
            items=self.strict_items,
            created_by=self.user,
        )
        order.status = business_models.PurchaseReturnStatusEnum.APPROVED
        order.save(update_fields=['status'])
        with self.assertRaises(ValueError):
            services.update_purchase_return_order(
                purchase_return_order=order,
                items=self.strict_items,
            )
