from datetime import date, timedelta
from decimal import Decimal
import io

from django.core.exceptions import ValidationError
from django.test import TestCase
from rest_framework.test import APIClient

from apps.accounting.models import (
    Account,
    EquipmentAsset,
    FinancialYearOpeningCarryForward,
    LedgerEntry,
    OpeningBalanceAdjustmentMapping,
    OpeningBalanceCorrection,
    OpeningBalanceReconciliation,
    OpeningBalanceVoucher,
    OpeningCategory,
    DirectionChoice,
    Party,
    PartyLedgerEntry,
    Voucher,
)
from apps.accounting.services import (
    FinancialYearCarryForwardService,
    LedgerService,
    OpeningBalanceCorrectionService,
    OpeningBalanceCreationService,
    OpeningBalanceDirectionService,
    OpeningBalanceImportService,
    OpeningBalanceMappingService,
    OpeningBalancePostingService,
    OpeningBalanceReconciliationService,
    OpeningBalanceValidationService,
    OpeningBalanceVoucherService,
    PostingService,
    ReportingService,
    VoucherService,
)
from apps.accounts_rbac.constants import Permissions, ROLE_PRESETS
from apps.accounts_rbac.models import CompanyMembership, Role, User
from apps.banking.models import Bank, BankBranch, BankReconciliationSession
from apps.banking.services import BankingService
from apps.loans.models import BankFacility
from apps.loans.services import LoanService
from apps.localization.bs_calendar import bs_to_ad
from apps.party_hub.models import OpenItem
from apps.party_hub.services import ReceivableService
from apps.tenancy.models import Company, FiscalYear


class EnterpriseOpeningBalanceTests(TestCase):
    def setUp(self):
        self.roles = {
            code: Role.objects.create(
                code=code,
                name=spec["name"],
                description=spec["description"],
                permissions=spec["permissions"],
                is_system=True,
            )
            for code, spec in ROLE_PRESETS.items()
        }
        self.company = Company.objects.create(
            code="OBCO1", name="Himalayan Infra Opening Test Ltd", base_currency="NPR", multi_currency_enabled=True
        )
        self.fy = FiscalYear.objects.create(
            company=self.company,
            name="2083/84",
            start_date=bs_to_ad(2083, 4, 1),
            end_date=bs_to_ad(2084, 3, 31),
            is_current=True,
        )
        self.fy.generate_nepal_periods(2083)
        self.cutoff = self.fy.start_date

        self.admin = User.objects.create_user(username="ob_admin", email="admin@ob.test", password="Password@123")
        self.fin_mgr = User.objects.create_user(username="ob_finmgr", email="fin@ob.test", password="Password@123")
        self.accountant = User.objects.create_user(username="ob_acct", email="acct@ob.test", password="Password@123")

        CompanyMembership.objects.create(user=self.admin, company=self.company, role=self.roles["COMPANY_ADMIN"], is_default=True)
        CompanyMembership.objects.create(user=self.fin_mgr, company=self.company, role=self.roles["FINANCE_MANAGER"], is_default=True)
        CompanyMembership.objects.create(user=self.accountant, company=self.company, role=self.roles["ACCOUNTANT"], is_default=True)

        # Core Chart of Accounts
        self.debtors = Account.objects.create(
            company=self.company, code="1100", name="Sundry Debtors", account_type=Account.AccountType.ASSET,
            control_role=Account.ControlRole.SUNDRY_DEBTORS, is_control_account=True, requires_subledger=True, allow_direct_posting=True,
        )
        self.creditors = Account.objects.create(
            company=self.company, code="2010", name="Sundry Creditors", account_type=Account.AccountType.LIABILITY,
            control_role=Account.ControlRole.SUNDRY_CREDITORS, is_control_account=True, requires_subledger=True, allow_direct_posting=True,
        )
        self.inventory_acc = Account.objects.create(
            company=self.company, code="1300", name="Site Inventory Stock", account_type=Account.AccountType.ASSET,
            control_role=Account.ControlRole.INVENTORY, allow_direct_posting=True,
        )
        self.fixed_asset_acc = Account.objects.create(
            company=self.company, code="1510", name="Heavy Construction Machinery", account_type=Account.AccountType.ASSET,
            allow_direct_posting=True,
        )
        self.accum_dep_acc = Account.objects.create(
            company=self.company, code="1590", name="Accumulated Depreciation — Machinery",
            account_type=Account.AccountType.ASSET, account_class=Account.AccountClass.CONTRA_ASSET,
            control_role=Account.ControlRole.ACCUM_DEPRECIATION, allow_direct_posting=True,
        )
        self.revenue_acc = Account.objects.create(
            company=self.company, code="4010", name="Contract Revenue", account_type=Account.AccountType.INCOME, allow_direct_posting=True,
        )
        self.expense_acc = Account.objects.create(
            company=self.company, code="5010", name="Direct Construction Expense", account_type=Account.AccountType.EXPENSE, allow_direct_posting=True,
        )
        self.equity_cap = Account.objects.create(
            company=self.company, code="3010", name="Share Capital", account_type=Account.AccountType.EQUITY, allow_direct_posting=True,
        )

        self.bank = Bank.objects.create(company=self.company, name="Nabil Bank", short_code="NABIL")
        self.bbranch = BankBranch.objects.create(bank=self.bank, branch_code="KTM", name="Kathmandu")

    def _client(self, user):
        c = APIClient()
        c.force_authenticate(user=user)
        c.defaults["HTTP_X_COMPANY_ID"] = str(self.company.id)
        return c

    # Test 1: Automatic Debit/Credit Classification Engine
    def test_01_automatic_direction_classification(self):
        self.assertEqual(OpeningBalanceDirectionService.get_default_direction(entity_kind="BANK")["default_direction"], DirectionChoice.DR)
        self.assertEqual(OpeningBalanceDirectionService.get_default_direction(entity_kind="CASH")["default_direction"], DirectionChoice.DR)
        self.assertEqual(OpeningBalanceDirectionService.get_default_direction(party_type=Party.PartyType.CUSTOMER)["default_direction"], DirectionChoice.DR)
        self.assertEqual(OpeningBalanceDirectionService.get_default_direction(party_type=Party.PartyType.SUPPLIER)["default_direction"], DirectionChoice.CR)
        self.assertEqual(OpeningBalanceDirectionService.get_default_direction(entity_kind="LOANS")["default_direction"], DirectionChoice.CR)
        self.assertEqual(OpeningBalanceDirectionService.get_default_direction(entity_kind="OD_CC")["default_direction"], DirectionChoice.CR)
        self.assertEqual(OpeningBalanceDirectionService.get_default_direction(account=self.accum_dep_acc)["default_direction"], DirectionChoice.CR)
        self.assertEqual(OpeningBalanceDirectionService.get_default_direction(account=self.inventory_acc)["default_direction"], DirectionChoice.DR)

    # Test 2: Bank Account Opening via Balanced GL Voucher (Single GL Truth)
    def test_02_bank_account_opening_creates_balanced_voucher_not_static_field(self):
        ba = BankingService.create_bank_account(
            company=self.company,
            user=self.fin_mgr,
            bank_branch=self.bbranch,
            account_name="Nabil Project Operating",
            account_number="010101889900",
            account_type="CURRENT",
            purpose="GENERAL",
            currency="NPR",
            opening_balance=Decimal("1500000.00"),
        )
        ba.gl_account.refresh_from_db()
        # Static opening_debit must remain 0 so ReportingService never double counts
        self.assertEqual(ba.gl_account.opening_debit, Decimal("0.00"))
        self.assertEqual(BankingService.get_gl_balance(ba.gl_account), Decimal("1500000.00"))
        ob = OpeningBalanceVoucher.objects.get(company=self.company, source_entity_type="BankAccount", source_entity_id=str(ba.id))
        self.assertEqual(ob.status, OpeningBalanceVoucher.Status.POSTED)
        self.assertEqual(ob.lines.first().adjustment_account.code, "390002")
        tb = ReportingService.get_trial_balance(company=self.company)
        self.assertTrue(tb["is_balanced"])
        row = next(r for r in tb["rows"] if r["account_id"] == str(ba.gl_account.id))
        self.assertEqual(Decimal(row["opening_debit"]), Decimal("1500000.00"))

    # Test 3: Cash Vault & Petty Cash Opening
    def test_03_cash_vault_opening_balanced(self):
        ca = BankingService.create_cash_account(
            company=self.company,
            user=self.fin_mgr,
            code="VAULT-HO",
            name="Head Office Main Vault",
            cash_type="HEAD_OFFICE",
            currency="NPR",
            imprest_limit=Decimal("500000.00"),
            opening_balance=Decimal("250000.00"),
        )
        self.assertEqual(ca.gl_account.control_role, Account.ControlRole.CASH)
        self.assertEqual(BankingService.get_gl_balance(ca.gl_account), Decimal("250000.00"))
        self.assertEqual(LedgerEntry.objects.filter(account=ca.gl_account, voucher__voucher_type="OPENING_BALANCE").count(), 1)

    # Test 4 & 5: Customer Lump-Sum & Bill-Wise Multi-Invoice Opening (1 Atomic Voucher -> Distinct OpenItems)
    def test_04_and_05_customer_lump_sum_and_billwise_open_items(self):
        prof = ReceivableService.register_customer(
            company=self.company,
            user=self.fin_mgr,
            party_data={
                "code": "CUST-BLD",
                "name": "Kathmandu Expressway Corp",
                "opening_balance": Decimal("1000000.00"),
                "opening_date": self.cutoff,
                "bill_items": [
                    {"invoice_ref": "RA-01", "invoice_date": self.cutoff - timedelta(days=40), "due_date": self.cutoff - timedelta(days=10), "outstanding_amount": Decimal("600000.00")},
                    {"invoice_ref": "RA-02", "invoice_date": self.cutoff - timedelta(days=15), "due_date": self.cutoff + timedelta(days=15), "outstanding_amount": Decimal("400000.00")},
                ],
            },
            profile_data={},
        )
        items = OpenItem.objects.filter(company=self.company, party=prof.party, hub_side=OpenItem.HubSide.RECEIVABLE)
        self.assertEqual(items.count(), 2)
        self.assertEqual(set(items.values_list("document_no", flat=True)), {"RA-01", "RA-02"})
        self.assertEqual(PartyLedgerEntry.objects.filter(company=self.company, party=prof.party).count(), 2)
        recon = OpeningBalanceReconciliationService.reconcile_subledgers_and_clearing(company=self.company)
        self.assertEqual(Decimal(recon["ar_control_gl"]), Decimal("1000000.00"))
        self.assertEqual(Decimal(recon["ar_variance"]), Decimal("0.00"))

        # Mismatched bill sum must fail validation cleanly
        with self.assertRaises(ValidationError):
            ReceivableService.register_customer(
                company=self.company,
                user=self.fin_mgr,
                party_data={
                    "code": "CUST-BAD",
                    "name": "Bad Sum Client",
                    "opening_balance": Decimal("500000.00"),
                    "bill_items": [{"invoice_ref": "X-1", "outstanding_amount": Decimal("300000.00")}],
                },
                profile_data={},
            )

    # Test 6 & 7: Opposite-Direction Party Guards (Customer Advance & Supplier Advance Reclassification)
    def test_06_and_07_opposite_direction_party_advance_reclassification(self):
        # Customer with Credit balance -> Customer Advance Liability (2070)
        cust = Party.objects.create(
            company=self.company, code="CUST-ADV", name="Client Advance Co",
            party_type=Party.PartyType.CUSTOMER, control_account=self.debtors,
        )
        ob_c = OpeningBalanceCreationService.create_party_billwise_opening(
            company=self.company,
            user=self.fin_mgr,
            party=cust,
            lump_sum_amount=Decimal("450000.00"),
            direction="CR",
            opening_date=self.cutoff,
        )
        self.assertEqual(ob_c.lines.first().account.control_role, Account.ControlRole.CUSTOMER_ADVANCE)

        # Supplier with Debit balance -> Supplier Advance Asset (1180), plus normal Supplier Credit -> AP OpenItem
        sup_adv = Party.objects.create(
            company=self.company, code="SUP-ADV", name="Cement Supplier Advance",
            party_type=Party.PartyType.SUPPLIER, control_account=self.creditors,
        )
        ob_s = OpeningBalanceCreationService.create_party_billwise_opening(
            company=self.company,
            user=self.fin_mgr,
            party=sup_adv,
            lump_sum_amount=Decimal("200000.00"),
            direction="DR",
            opening_date=self.cutoff,
        )
        self.assertEqual(ob_s.lines.first().account.control_role, Account.ControlRole.SUPPLIER_ADVANCE)

        sup_ap = Party.objects.create(
            company=self.company, code="SUP-CR", name="Steel Mill Vendor",
            party_type=Party.PartyType.SUPPLIER, control_account=self.creditors,
        )
        ob_ap = OpeningBalanceCreationService.create_party_billwise_opening(
            company=self.company,
            user=self.fin_mgr,
            party=sup_ap,
            lump_sum_amount=Decimal("320000.00"),
            opening_date=self.cutoff,
        )
        self.assertEqual(ob_ap.lines.first().direction, DirectionChoice.CR)
        self.assertEqual(OpenItem.objects.filter(party=sup_ap, hub_side=OpenItem.HubSide.PAYABLE).count(), 1)

    # Test 8 & 9: Fixed Asset / Contra Depreciation + Loans / OD Facility Openings
    def test_08_and_09_fixed_asset_accum_dep_and_loan_facility_openings(self):
        c = self._client(self.admin)
        res = c.post(
            "/api/v1/equipment-assets/",
            {
                "code": "EXC-01",
                "name": "CAT 320 Excavator",
                "asset_category": "Heavy Machinery",
                "linked_asset_account": str(self.fixed_asset_acc.id),
                "opening_balance": "4500000.00",
                "opening_date": self.cutoff.isoformat(),
            },
            format="json",
        )
        self.assertEqual(res.status_code, 201)
        self.assertEqual(OpeningBalanceVoucher.objects.filter(company=self.company, source_entity_type="EquipmentAsset").count(), 1)

        # Accumulated Depreciation (Contra-Asset Cr)
        ob_dep = OpeningBalanceCreationService.create_single_account_opening(
            company=self.company,
            user=self.fin_mgr,
            account=self.accum_dep_acc,
            amount=Decimal("900000.00"),
            opening_date=self.cutoff,
        )
        self.assertEqual(ob_dep.lines.first().direction, DirectionChoice.CR)

        # Loan Facility Creation with opening balance
        ba = BankingService.create_bank_account(
            company=self.company, user=self.fin_mgr, bank_branch=self.bbranch,
            account_name="Loan Funding", account_number="8877665544", account_type="CURRENT",
            purpose="GENERAL", currency="NPR", opening_balance=Decimal("0.00"),
        )
        fac = LoanService.create_facility(
            company=self.company,
            user=self.fin_mgr,
            data={
                "facility_code": "TL-OPEN-01",
                "facility_name": "Equipment Term Loan",
                "facility_type": BankFacility.FacilityType.TERM_LOAN,
                "bank_account": ba,
                "sanction_date": self.cutoff,
                "maturity_date": self.cutoff + timedelta(days=730),
                "sanctioned_limit": Decimal("5000000.00"),
                "opening_balance": Decimal("2500000.00"),
            },
        )
        self.assertEqual(LoanService.get_outstanding_principal(fac), Decimal("2500000.00"))

    # Test 10 & 11: COA New Account API + Zero-Value Guard
    def test_10_and_11_coa_api_opening_and_zero_value_guard(self):
        c = self._client(self.fin_mgr)
        res = c.post(
            "/api/v1/accounts/",
            {
                "code": "1099",
                "name": "Security Deposit Asset",
                "account_type": "ASSET",
                "opening_balance": "125000.00",
                "opening_date": self.cutoff.isoformat(),
            },
            format="json",
        )
        self.assertEqual(res.status_code, 201)
        acc = Account.objects.get(company=self.company, code="1099")
        self.assertEqual(acc.opening_debit, Decimal("0.00"))
        self.assertEqual(LedgerEntry.objects.filter(account=acc).count(), 1)

        # Zero amount must create account with zero OpeningBalanceVoucher
        before_cnt = OpeningBalanceVoucher.objects.count()
        res_zero = c.post(
            "/api/v1/accounts/",
            {"code": "1098", "name": "Zero Opening Account", "account_type": "ASSET", "opening_balance": "0.00"},
            format="json",
        )
        self.assertEqual(res_zero.status_code, 201)
        self.assertEqual(OpeningBalanceVoucher.objects.count(), before_cnt)

    # Test 12: Block Income/Expense as Adjustment Account
    def test_12_block_income_expense_adjustment_account(self):
        with self.assertRaises(ValidationError):
            OpeningBalanceMappingService.set_mapping(
                company=self.company,
                category=OpeningCategory.BANK,
                adjustment_account=self.revenue_acc,
                user=self.fin_mgr,
            )
        with self.assertRaises(ValidationError):
            OpeningBalanceMappingService.set_mapping(
                company=self.company,
                category=OpeningCategory.CREDITORS,
                adjustment_account=self.expense_acc,
                user=self.fin_mgr,
            )

    # Test 13 & 14: Direction Override RBAC/Reason + Mid-Year Cut-off Live Account Guard
    def test_13_and_14_direction_override_and_midyear_cutoff_guards(self):
        # Accountant lacks direction override permission & empty reason rejected
        with self.assertRaises(ValidationError):
            OpeningBalanceCreationService.create_single_account_opening(
                company=self.company,
                user=self.accountant,
                account=self.inventory_acc,
                amount=Decimal("50000.00"),
                opening_date=self.cutoff,
                direction=DirectionChoice.CR,
                override_reason="",
            )
        # Finance manager with reason succeeds
        ob = OpeningBalanceCreationService.create_single_account_opening(
            company=self.company,
            user=self.fin_mgr,
            account=self.inventory_acc,
            amount=Decimal("50000.00"),
            opening_date=self.cutoff,
            direction=DirectionChoice.CR,
            override_reason="Shortage adjustment pending physical verification",
        )
        self.assertTrue(ob.lines.first().is_direction_overridden)

        # Date after conversion_cutoff_date blocked without migration_override_reason / permission
        future_dt = self.cutoff + timedelta(days=45)
        with self.assertRaises(ValidationError):
            OpeningBalanceCreationService.create_single_account_opening(
                company=self.company,
                user=self.accountant,
                account=self.equity_cap,
                amount=Decimal("100000.00"),
                opening_date=future_dt,
                migration_override_reason="",
            )
        with self.assertRaises(ValidationError):
            OpeningBalanceCreationService.create_single_account_opening(
                company=self.company,
                user=self.accountant,
                account=self.equity_cap,
                amount=Decimal("100000.00"),
                opening_date=future_dt,
                migration_override_reason="Attempted by unprivileged user",
            )
        # Admin with permission & reason succeeds
        ob_mid = OpeningBalanceCreationService.create_single_account_opening(
            company=self.company,
            user=self.admin,
            account=self.equity_cap,
            amount=Decimal("100000.00"),
            opening_date=future_dt,
            migration_override_reason="Approved Capital Infusion Backlog",
        )
        self.assertFalse(ob_mid.is_historical_migration)

    # Test 15 & 16: Draft Approval Workflow + Immutable Posted Voucher Reversal & Replacement Correction
    def test_15_and_16_approval_workflow_and_reversal_correction(self):
        ob = OpeningBalanceCreationService.create_single_account_opening(
            company=self.company,
            user=self.accountant,
            account=self.inventory_acc,
            amount=Decimal("400000.00"),
            opening_date=self.cutoff,
            auto_post=False,
        )
        self.assertEqual(ob.status, OpeningBalanceVoucher.Status.DRAFT)
        OpeningBalanceVoucherService.submit(ob=ob, user=self.accountant)
        OpeningBalanceVoucherService.approve(ob=ob, user=self.fin_mgr)
        OpeningBalancePostingService.post_ob_voucher(ob=ob, user=self.fin_mgr)
        ob.refresh_from_db()
        self.assertEqual(ob.status, OpeningBalanceVoucher.Status.POSTED)

        # Unprivileged user cannot reverse
        with self.assertRaises(ValidationError):
            OpeningBalanceCorrectionService.correct_posted_opening(
                ob=ob, user=self.accountant, reason="Unauthorized edit attempt", corrected_amount=Decimal("350000.00")
            )

        # Finance Manager reverses + posts replacement (400k -> 550k)
        corr = OpeningBalanceCorrectionService.correct_posted_opening(
            ob=ob,
            user=self.fin_mgr,
            reason="Verified stock valuation sheet adjustment",
            corrected_amount=Decimal("550000.00"),
        )
        ob.refresh_from_db()
        self.assertEqual(ob.status, OpeningBalanceVoucher.Status.REVERSED)
        self.assertEqual(corr.replacement_ob_voucher.status, OpeningBalanceVoucher.Status.POSTED)
        # Net GL on Inventory must equal 550,000.00
        led = LedgerService.get_account_ledger(company=self.company, account=self.inventory_acc)
        self.assertEqual(Decimal(led["closing_balance"]), Decimal("550000.00"))

    # Test 17: Bank Statement & Physical Cash Count Opening Reconciliations
    def test_17_bank_statement_and_cash_physical_opening_reconciliation(self):
        ba = BankingService.create_bank_account(
            company=self.company, user=self.fin_mgr, bank_branch=self.bbranch,
            account_name="Recon Bank", account_number="5544332211", account_type="CURRENT",
            purpose="GENERAL", currency="NPR", opening_balance=Decimal("800000.00"),
        )
        # Statement = 850,000; Deposits in transit = 50,000; Unpresented cheques = 100,000 -> Adjusted = 800,000 (0 variance!)
        rec_b = OpeningBalanceReconciliationService.reconcile_bank_opening(
            company=self.company,
            user=self.fin_mgr,
            bank_account=ba,
            statement_opening_balance=Decimal("850000.00"),
            reconciliation_date=self.cutoff,
            deposits_in_transit=Decimal("50000.00"),
            unpresented_cheques=Decimal("100000.00"),
        )
        self.assertEqual(rec_b.variance_amount, Decimal("0.00"))
        self.assertEqual(rec_b.status, "RECONCILED")
        self.assertTrue(BankReconciliationSession.objects.filter(company=self.company, bank_account=ba, is_opening_recon=True).exists())

        ca = BankingService.create_cash_account(
            company=self.company, user=self.fin_mgr, code="PETTY-1", name="Site Petty Cash",
            cash_type="IMPREST", currency="NPR", imprest_limit=Decimal("100000.00"), opening_balance=Decimal("65000.00"),
        )
        rec_c = OpeningBalanceReconciliationService.reconcile_cash_physical(
            company=self.company, user=self.fin_mgr, cash_account=ca,
            physical_count_balance=Decimal("64500.00"), reconciliation_date=self.cutoff, explanation="NPR 500 unvouchered slip",
        )
        self.assertEqual(rec_c.variance_amount, Decimal("500.00"))
        self.assertEqual(rec_c.status, "VARIANCE_OPEN")

    # Test 18: Bulk CSV Import Validation & Conversion
    def test_18_bulk_csv_import_validation_and_conversion(self):
        bad_csv = (
            "account_code,party_code,opening_date,debit,credit,currency,reference_no\n"
            "NOPE999,,2083-04-01,1000,0,NPR,BAD1\n"
            f"1100,,{self.cutoff.isoformat()},5000,0,NPR,NOPARTY\n"
        ).encode("utf-8")
        batch_bad = OpeningBalanceImportService.validate_upload(
            company=self.company, user=self.fin_mgr, batch_name="Bad Batch", file_bytes=bad_csv, file_ext="csv"
        )
        self.assertEqual(batch_bad.error_rows, 2)
        with self.assertRaises(ValidationError):
            OpeningBalanceImportService.convert_batch_to_voucher(batch=batch_bad, user=self.fin_mgr)

        good_csv = (
            "account_code,party_code,opening_date,debit,credit,currency,reference_no\n"
            f"1300,,{self.cutoff.isoformat()},300000,0,NPR,IMP-STK\n"
            f"3010,,{self.cutoff.isoformat()},0,300000,NPR,IMP-CAP\n"
        ).encode("utf-8")
        batch_ok = OpeningBalanceImportService.validate_upload(
            company=self.company, user=self.fin_mgr, batch_name="Valid Migration", file_bytes=good_csv, file_ext="csv"
        )
        self.assertEqual(batch_ok.error_rows, 0)
        ob = OpeningBalanceImportService.convert_batch_to_voucher(batch=batch_ok, user=self.fin_mgr, auto_post=True)
        self.assertEqual(ob.status, OpeningBalanceVoucher.Status.POSTED)
        self.assertEqual(ob.lines.count(), 2)

    # Test 19: API Summary, Control Tie-Out & CSV/XLSX Exports
    def test_19_api_summary_and_report_exports(self):
        OpeningBalanceCreationService.create_single_account_opening(
            company=self.company, user=self.fin_mgr, account=self.inventory_acc, amount=Decimal("100000.00"), opening_date=self.cutoff
        )
        c = self._client(self.fin_mgr)
        self.assertEqual(c.get("/api/v1/opening-balances/summary/").status_code, 200)
        self.assertEqual(c.get("/api/accounting/opening-balances/summary/").status_code, 200)
        r_csv = c.get("/api/v1/opening-balances/reports/SUMMARY/export/?ext=csv")
        r_xlsx = c.get("/api/v1/opening-balances/reports/SUMMARY/export/?ext=xlsx")
        self.assertEqual(r_csv.status_code, 200)
        self.assertEqual(r_xlsx.status_code, 200)

    # Test 20: Financial Year End Carry-Forward & Duplicate Guard
    def test_20_financial_year_carry_forward_and_duplicate_block(self):
        # Post opening + a Revenue entry in current FY (2083/84)
        OpeningBalanceCreationService.create_single_account_opening(
            company=self.company, user=self.fin_mgr, account=self.inventory_acc, amount=Decimal("500000.00"), opening_date=self.cutoff
        )
        v_sale = VoucherService.create_draft(
            company=self.company,
            user=self.fin_mgr,
            data={"voucher_type": "JOURNAL", "voucher_date": self.cutoff + timedelta(days=10), "narration": "FY Profit Test"},
            lines_data=[
                {"account": self.debtors, "party": Party.objects.create(company=self.company, code="C-CF", name="CF Client", control_account=self.debtors), "debit": Decimal("200000.00"), "credit": Decimal("0.00")},
                {"account": self.revenue_acc, "debit": Decimal("0.00"), "credit": Decimal("200000.00")},
            ],
        )
        v_sale.status = Voucher.Status.APPROVED
        v_sale.save(update_fields=["status"])
        PostingService.post_voucher(voucher=v_sale, user=self.fin_mgr)

        # Next FY (2084/85)
        next_fy = FiscalYear.objects.create(
            company=self.company,
            name="2084/85",
            start_date=bs_to_ad(2084, 4, 1),
            end_date=bs_to_ad(2085, 3, 31),
        )
        next_fy.generate_nepal_periods(2084)

        cf = FinancialYearCarryForwardService.execute_carry_forward(
            company=self.company,
            user=self.fin_mgr,
            source_fiscal_year=self.fy,
            target_fiscal_year=next_fy,
        )
        self.assertEqual(cf.status, "POSTED")
        self.assertEqual(cf.total_debit, cf.total_credit)
        self.assertGreaterEqual(cf.accounts_carried, 3)

        # Duplicate carry-forward must fail!
        with self.assertRaises(ValidationError):
            FinancialYearCarryForwardService.execute_carry_forward(
                company=self.company,
                user=self.fin_mgr,
                source_fiscal_year=self.fy,
                target_fiscal_year=next_fy,
            )

    # Test 21: VoucherLine bill_ref db_default + Machine Income Voucher (Single Entry Cash/Bank & Double Entry)
    def test_21_bill_ref_default_and_machine_income_single_and_double_entry(self):
        from django.db import connection
        from apps.accounting.models import VoucherLine
        from apps.accounting.services.voucher_design_service import VoucherDesignService

        # 1. Verify DB schema default on accounting_voucherline.bill_ref (prevents MariaDB 1364)
        v_raw = Voucher.objects.create(
            company=self.company,
            fiscal_year=self.fy,
            fiscal_period=self.fy.periods.first(),
            voucher_type=Voucher.VoucherType.JOURNAL,
            voucher_date=self.cutoff,
            narration="Raw line test",
            created_by=self.fin_mgr,
        )
        vl = VoucherLine.objects.create(
            voucher=v_raw, line_no=1, account=self.inventory_acc, debit=Decimal("100.00"), credit=Decimal("0.00")
        )
        self.assertEqual(vl.bill_ref, "")
        with connection.cursor() as cur:
            cur.execute(
                "INSERT INTO accounting_voucherline (id, line_no, debit, credit, work_activity, employee_ref, expense_scope, quantity, unit, unit_rate, tax_rate, tds_rate, retention_pct, is_auto_generated, description, account_id, voucher_id) "
                "VALUES (REPLACE(UUID(), '-', ''), 2, 0.00, 100.00, '', '', '', 0.000, '', 0.00, 0.00, 0.00, 0.00, 0, '', %s, %s)",
                [str(self.equity_cap.id).replace("-", ""), str(v_raw.id).replace("-", "")],
            )

        # 2. Machine Income Voucher in Blueprint Catalog + Types Catalog
        VoucherDesignService.ensure_default_design_studio_catalog(self.company)
        c = self._client(self.fin_mgr)
        bp_res = c.get("/api/v1/voucher-blueprints/resolved/?voucher_type=MACHINE_INCOME")
        self.assertEqual(bp_res.status_code, 200)
        self.assertEqual(bp_res.json()["blueprint"]["voucher_type"], "MACHINE_INCOME")

        # 3. Single Entry Mode: Cash/Bank Top + Machine Income Credit (no customer party)
        cash_acc = Account.objects.create(
            company=self.company, code="1010", name="Site Cash", account_type=Account.AccountType.ASSET,
            control_role=Account.ControlRole.CASH, allow_direct_posting=True,
        )
        mach_inc_acc = Account.objects.create(
            company=self.company, code="4150", name="Machine Hire Income", account_type=Account.AccountType.INCOME,
            control_role=Account.ControlRole.OTHER_INCOME, allow_direct_posting=True,
        )
        eq = EquipmentAsset.objects.create(
            company=self.company, code="EXC-M1", name="Komatsu PC200", hourly_rate=Decimal("3500.00"),
            linked_asset_account=self.fixed_asset_acc,
        )
        r_single = c.post(
            "/api/v1/vouchers/",
            {
                "voucher_type": "MACHINE_INCOME",
                "voucher_date": self.cutoff.isoformat(),
                "entry_mode": "SINGLE_ENTRY",
                "single_entry_account": str(cash_acc.id),
                "narration": "Cash excavator rental 10 hours",
                "lines": [
                    {"account": str(mach_inc_acc.id), "amount": "35000.00", "equipment": str(eq.id), "description": "PC200 10 hrs @ 3500"}
                ],
            },
            format="json",
        )
        self.assertEqual(r_single.status_code, 201, r_single.content)
        v_single_id = r_single.json()["id"]
        c_app = self._client(self.admin)
        self.assertEqual(c.post(f"/api/v1/vouchers/{v_single_id}/submit/", {}, format="json").status_code, 200)
        self.assertEqual(c_app.post(f"/api/v1/vouchers/{v_single_id}/approve/", {}, format="json").status_code, 200)
        self.assertEqual(c_app.post(f"/api/v1/vouchers/{v_single_id}/post/", {}, format="json").status_code, 200)
        self.assertEqual(
            Decimal(LedgerService.get_account_ledger(company=self.company, account=cash_acc)["closing_balance"]),
            Decimal("35000.00"),
        )

        # 4. Double Entry Customer Credit Mode (Customer Debtors Debit + Machine Income Credit -> OpenItem)
        cust = Party.objects.create(
            company=self.company, code="CUST-MCH", name="Pokhara Road Builders",
            party_type=Party.PartyType.CUSTOMER, control_account=self.debtors,
        )
        r_credit = c.post(
            "/api/v1/vouchers/",
            {
                "voucher_type": "MACHINE_INCOME",
                "voucher_date": self.cutoff.isoformat(),
                "entry_mode": "DOUBLE_ENTRY",
                "party": str(cust.id),
                "narration": "Credit excavator rental bill",
                "scenario": {
                    "entry_style": "CREDIT",
                    "taxable_amount": "50000.00",
                    "income_account": str(mach_inc_acc.id),
                    "equipment": str(eq.id),
                },
            },
            format="json",
        )
        self.assertEqual(r_credit.status_code, 201, r_credit.content)
        v_credit_id = r_credit.json()["id"]
        self.assertEqual(c.post(f"/api/v1/vouchers/{v_credit_id}/submit/", {}, format="json").status_code, 200)
        self.assertEqual(c_app.post(f"/api/v1/vouchers/{v_credit_id}/approve/", {}, format="json").status_code, 200)
        self.assertEqual(c_app.post(f"/api/v1/vouchers/{v_credit_id}/post/", {}, format="json").status_code, 200)
        self.assertEqual(
            OpenItem.objects.filter(company=self.company, voucher_id=v_credit_id, party=cust, original_amount=Decimal("50000.00")).count(),
            1,
        )

        # 5. Double Entry Explicit Dr / Cr Grid Mode
        r_grid = c.post(
            "/api/v1/vouchers/",
            {
                "voucher_type": "MACHINE_INCOME",
                "voucher_date": self.cutoff.isoformat(),
                "entry_mode": "DOUBLE_ENTRY",
                "narration": "Explicit Dr/Cr machine income split",
                "lines": [
                    {"account": str(cash_acc.id), "debit": "15000.00", "credit": "0.00", "equipment": str(eq.id)},
                    {"account": str(mach_inc_acc.id), "debit": "0.00", "credit": "15000.00", "equipment": str(eq.id)},
                ],
            },
            format="json",
        )
        self.assertEqual(r_grid.status_code, 201, r_grid.content)


