from datetime import date
from decimal import Decimal
from django.core.exceptions import ValidationError
from django.test import TestCase

from apps.accounts_rbac.models import User
from apps.accounting.models import Account, LedgerEntry, Party
from apps.projects.models import CostCode, Project
from apps.tenancy.models import Company, FiscalYear
from .models import ItemCategory, ItemMaster, StockMovement, UnitOfMeasure, Warehouse
from .services import InventoryService
from .valuation import InventoryValuationService


class EnterpriseInventoryValuationTests(TestCase):
    def setUp(self):
        self.company = Company.objects.create(code="INVT", name="Inv Co", base_currency="NPR")
        self.fy = FiscalYear.objects.create(
            company=self.company, name="2083/84", start_date=date(2026, 7, 16), end_date=date(2027, 7, 15), is_current=True
        )
        self.fy.generate_nepal_periods(2083)
        self.user = User.objects.create_user(username="invu", email="invu@maya.local", password="Password@123", is_superuser=True)

        self.acc_inv = Account.objects.create(company=self.company, code="1200", name="Inventory", account_type="ASSET", control_role=Account.ControlRole.INVENTORY)
        self.acc_wip = Account.objects.create(company=self.company, code="1400", name="Project WIP", account_type="ASSET", control_role=Account.ControlRole.PROJECT_WIP)
        self.acc_grni = Account.objects.create(company=self.company, code="2090", name="GRNI", account_type="LIABILITY", control_role=Account.ControlRole.GRNI)

        self.project = Project.objects.create(company=self.company, code="P1", name="Bridge")
        self.cc = CostCode.objects.create(company=self.company, code="MAT", name="Material", category="MATERIAL")
        self.wh1 = Warehouse.objects.create(company=self.company, code="W1", name="Main Store")
        self.wh2 = Warehouse.objects.create(company=self.company, code="W2", name="Site Store", project=self.project)
        self.vendor = Party.objects.create(company=self.company, party_type="SUPPLIER", code="SUP1", name="Steel Co")

        cat = ItemCategory.objects.create(company=self.company, code="STL", name="Steel")
        unit = UnitOfMeasure.objects.create(company=self.company, code="Kg", name="Kilogram")
        self.item_fifo = ItemMaster.objects.create(
            company=self.company, item_code="REBAR-16", name="16mm Rebar", category=cat, primary_unit=unit,
            valuation_method=ItemMaster.ValuationMethod.FIFO, inventory_account=self.acc_inv, expense_wip_account=self.acc_wip,
        )

    def test_fifo_cost_depletion_negative_stock_block_and_single_wip_posting(self):
        # Receive Batch 1: 100 @ 700, Batch 2: 100 @ 800
        InventoryValuationService.receive_stock(
            company=self.company, warehouse=self.wh1, item=self.item_fifo, qty=Decimal("100"), unit_cost=Decimal("700.00"),
            movement_date=date(2026, 11, 1), movement_type=StockMovement.MovementType.GRN_RECEIPT, reference_no="GRN-A", user=self.user, batch_no="B1",
        )
        InventoryValuationService.receive_stock(
            company=self.company, warehouse=self.wh1, item=self.item_fifo, qty=Decimal("100"), unit_cost=Decimal("800.00"),
            movement_date=date(2026, 11, 5), movement_type=StockMovement.MovementType.GRN_RECEIPT, reference_no="GRN-B", user=self.user, batch_no="B2",
        )

        # Negative stock prevented
        with self.assertRaises(ValidationError):
            InventoryService.create_and_approve_issue(
                company=self.company, user=self.user,
                data={"issue_no": "ISS-TOO-BIG", "issue_date": date(2026, 11, 10), "warehouse": self.wh1, "project": self.project},
                lines_data=[{"item": self.item_fifo, "quantity": Decimal("250"), "cost_code": self.cc}],
                auto_approve=True,
            )

        # FIFO issue of 150 units = (100 * 700) + (50 * 800) = 110,000 -> Dr WIP / Cr Inventory
        issue = InventoryService.create_and_approve_issue(
            company=self.company, user=self.user,
            data={"issue_no": "ISS-1", "issue_date": date(2026, 11, 10), "warehouse": self.wh1, "project": self.project},
            lines_data=[{"item": self.item_fifo, "quantity": Decimal("150"), "cost_code": self.cc}],
            auto_approve=True,
        )
        self.assertEqual(issue.total_cost, Decimal("110000.00"))
        self.assertIsNotNone(issue.linked_voucher)
        wip_bal = sum(e.base_debit - e.base_credit for e in LedgerEntry.objects.filter(company=self.company, account=self.acc_wip))
        self.assertEqual(wip_bal, Decimal("110000.00"))

        rem_qty, rem_val = InventoryValuationService.get_item_warehouse_balance(self.company, self.wh1, self.item_fifo)
        self.assertEqual(rem_qty, Decimal("50.000"))
        self.assertEqual(rem_val, Decimal("40000.00"))

        # Inter-warehouse transfer
        InventoryService.transfer_stock(
            company=self.company, user=self.user,
            data={"transfer_no": "TRF-1", "transfer_date": date(2026, 11, 12), "from_warehouse": self.wh1, "to_warehouse": self.wh2, "item": self.item_fifo, "quantity": Decimal("20")},
        )
        q2, _ = InventoryValuationService.get_item_warehouse_balance(self.company, self.wh2, self.item_fifo)
        self.assertEqual(q2, Decimal("20.000"))

