from decimal import Decimal
from django.test import TestCase
from rest_framework.test import APIClient

from apps.accounts_rbac.constants import ROLE_PRESETS
from apps.accounts_rbac.models import CompanyMembership, Role, User
from apps.accounting.models import Account, Party, Voucher
from apps.accounting.services import ApprovalService, PostingService
from apps.audit.models import AuditEvent
from apps.banking.models import Bank, BankAccount, BankBranch, BankTransaction, ChequeLeaf
from apps.banking.services import BankingService
from apps.localization.bs_calendar import bs_to_ad
from apps.tenancy.models import Company, FiscalYear
from apps.treasury.cheques.cancellations.service import ChequeCancellationService
from apps.treasury.cheques.cheque_books.service import ChequeBookService
from apps.treasury.cheques.cheque_leaves.service import ChequeLeafService
from apps.treasury.cheques.clearing.service import ChequeClearingService
from apps.treasury.cheques.gl_helpers import get_bank_transfer_in_transit_account


class BankTxnContraAndChequeSelectionTests(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="BTXN",
            name="Pragati Builders Pvt Ltd",
            pan_vat_no="604455667",
            base_currency="NPR",
        )
        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.tx_date = bs_to_ad(2083, 4, 25)

        self.fin_mgr = User.objects.create_user(username="bt_fin", email="fin@bt.local", password="Password@123")
        self.acct = User.objects.create_user(username="bt_acct", email="acct@bt.local", password="Password@123")
        CompanyMembership.objects.create(user=self.fin_mgr, company=self.company, role=self.roles["FINANCE_MANAGER"], is_default=True)
        CompanyMembership.objects.create(user=self.acct, company=self.company, role=self.roles["ACCOUNTANT"], is_default=True)

        # Same bank (Nepal Bank Ltd) with two separate accounts A and B!
        self.bank = Bank.objects.create(company=self.company, name="Nepal Bank Limited", short_code="NBL")
        self.branch = BankBranch.objects.create(bank=self.bank, branch_code="KTM", name="Kathmandu")
        self.ba_a = BankingService.create_bank_account(
            company=self.company, user=self.fin_mgr, bank_branch=self.branch,
            account_name="NBL Operating A", account_number="000100004521",
            account_type="CURRENT", purpose="GENERAL", currency="NPR", opening_balance=Decimal("1000000.00"),
        )
        self.ba_b = BankingService.create_bank_account(
            company=self.company, user=self.fin_mgr, bank_branch=self.branch,
            account_name="NBL Project B", account_number="000100008899",
            account_type="CURRENT", purpose="PROJECT_ESCROW", currency="NPR", opening_balance=Decimal("250000.00"),
        )
        self.cash_acc = BankingService.create_cash_account(
            company=self.company, user=self.fin_mgr, code="CASH-HO", name="Head Office Main Cash",
            cash_type="HEAD_OFFICE", currency="NPR", imprest_limit=Decimal("500000.00"),
        )
        # Opening cash balance = 300,000
        self.cash_acc.gl_account.opening_debit = Decimal("300000.00")
        self.cash_acc.gl_account.save(update_fields=["opening_debit"])

        self.book_a = ChequeBookService.register_book(
            company=self.company, bank_account=self.ba_a, book_code="CB-A",
            prefix="", start_number=2451, end_number=2456, issued_date=self.tx_date, actor=self.fin_mgr,
        )
        self.book_b = ChequeBookService.register_book(
            company=self.company, bank_account=self.ba_b, book_code="CB-B",
            prefix="", start_number=9001, end_number=9003, issued_date=self.tx_date, actor=self.fin_mgr,
        )

        self.cred_acc = Account.objects.create(
            company=self.company, code="2001", name="Sundry Creditors",
            account_type=Account.AccountType.LIABILITY, control_role=Account.ControlRole.SUNDRY_CREDITORS,
            requires_subledger=True, allow_direct_posting=True,
        )
        self.supplier = Party.objects.create(
            company=self.company, party_type=Party.PartyType.SUPPLIER, code="SUP-1",
            name="Panchakanya Steel", control_account=self.cred_acc,
        )

    def _client(self, user):
        c = APIClient()
        c.force_authenticate(user=user)
        c.credentials(HTTP_X_COMPANY_ID=str(self.company.id))
        return c

    def test_01_to_06_bank_linked_cheque_selection_filtering_and_concurrent_reservation(self):
        c_acct = self._client(self.acct)
        c_fin = self._client(self.fin_mgr)

        # 1. Selecting Cheque payment without bank account is blocked
        no_bank = c_acct.post(
            "/api/vouchers/payment/",
            {
                "voucher_date": self.tx_date.isoformat(),
                "payment_mode": "CHEQUE",
                "party": str(self.supplier.id),
                "amount": "15000.00",
            },
            format="json",
        )
        self.assertEqual(no_bank.status_code, 400)

        # 2 & 3. Bank A returns ONLY Bank A leaves (2451..2456), never Bank B (9001..9003)
        res_a = c_acct.get(f"/api/bank-accounts/{self.ba_a.id}/available-cheques/").json()
        nums_a = {r["cheque_number"] for r in res_a["results"]}
        self.assertEqual(nums_a, {"002451", "002452", "002453", "002454", "002455", "002456"})
        self.assertFalse(any(n.startswith("009") for n in nums_a))

        res_b = c_acct.get(f"/api/bank-accounts/{self.ba_b.id}/available-cheques/").json()
        nums_b = {r["cheque_number"] for r in res_b["results"]}
        self.assertEqual(nums_b, {"009001", "009002", "009003"})

        # Switching bank cannot use Bank B leaf under Bank A payment!
        leaf_b1 = ChequeLeaf.objects.get(bank_account=self.ba_b, cheque_number="009001")
        cross_bank = c_acct.post(
            "/api/vouchers/payment/",
            {
                "voucher_date": self.tx_date.isoformat(),
                "payment_mode": "CHEQUE",
                "bank_account_id": str(self.ba_a.id),
                "cheque_leaf_id": str(leaf_b1.id),
                "party": str(self.supplier.id),
                "amount": "12000.00",
            },
            format="json",
        )
        self.assertEqual(cross_bank.status_code, 400)

        # 4. Cancelled / Damaged / Lost leaves must NOT appear as available
        leaf_a2 = ChequeLeaf.objects.get(bank_account=self.ba_a, cheque_number="002452")
        leaf_a3 = ChequeLeaf.objects.get(bank_account=self.ba_a, cheque_number="002453")
        ChequeLeafService.mark_leaf_unusable(leaf=leaf_a2, kind="CANCELLED", user=self.fin_mgr, reason="Misprint")
        ChequeLeafService.mark_leaf_unusable(leaf=leaf_a3, kind="LOST", user=self.fin_mgr, reason="Lost leaf")

        # 5 & 6. Atomic Reservation & Blocking Second User
        leaf_a1 = ChequeLeaf.objects.get(bank_account=self.ba_a, cheque_number="002451")
        r1 = c_acct.post(f"/api/cheques/{leaf_a1.id}/reserve/", {"reason": "Holding for supplier bill"}, format="json")
        self.assertEqual(r1.status_code, 200)
        # Second user trying to reserve the SAME cheque leaf MUST be rejected
        r2 = c_fin.post(f"/api/cheques/{leaf_a1.id}/reserve/", {"reason": "Second user clash"}, format="json")
        self.assertEqual(r2.status_code, 400)

        avail_after = {
            r["cheque_number"]
            for r in c_acct.get(f"/api/bank-accounts/{self.ba_a.id}/available-cheques/").json()["results"]
        }
        self.assertSetEqual(avail_after, {"002454", "002455", "002456"})

        # Release reservation restores leaf to AVAILABLE
        rel = c_acct.post(f"/api/cheques/{leaf_a1.id}/release-reservation/", {"reason": "Released"}, format="json")
        self.assertEqual(rel.status_code, 200)
        avail_restored = {
            r["cheque_number"]
            for r in c_acct.get(f"/api/bank-accounts/{self.ba_a.id}/available-cheques/").json()["results"]
        }
        self.assertIn("002451", avail_restored)

        # 8. Frozen account blocks available cheques & payments
        self.ba_b.status = BankAccount.Status.FROZEN
        self.ba_b.save()
        frozen_chk = c_acct.get(f"/api/bank-accounts/{self.ba_b.id}/available-cheques/")
        self.assertEqual(frozen_chk.status_code, 400)

    def test_09_to_14_contra_payment_cheque_lifecycle_and_gl_agreement(self):
        c_acct = self._client(self.acct)
        c_fin = self._client(self.fin_mgr)

        # 9. Cash-to-Bank Contra -> Dr Bank A (+100,000), Cr Cash (-100,000)
        c2b = c_acct.post(
            "/api/vouchers/contra/",
            {
                "contra_type": "CASH_TO_BANK",
                "voucher_date": self.tx_date.isoformat(),
                "cash_account_id": str(self.cash_acc.id),
                "destination_bank_account_id": str(self.ba_a.id),
                "amount": "100000.00",
                "reference_no": "DEP-CASH-01",
            },
            format="json",
        )
        self.assertEqual(c2b.status_code, 201, c2b.content)
        v_c2b = Voucher.objects.get(id=c2b.json()["id"])
        VoucherService = c_acct.post(f"/api/vouchers/{v_c2b.id}/submit/")
        self.assertEqual(VoucherService.status_code, 200)
        self.assertEqual(c_fin.post(f"/api/vouchers/{v_c2b.id}/approve/").status_code, 200)
        self.assertEqual(c_fin.post(f"/api/vouchers/{v_c2b.id}/post/").status_code, 200)

        self.assertEqual(BankingService.get_gl_balance(self.ba_a.gl_account), Decimal("1100000.00"))
        self.assertEqual(BankingService.get_gl_balance(self.cash_acc.gl_account), Decimal("200000.00"))

        # 10. Bank-to-Cash Contra by Cheque -> strictly from Source Bank A!
        leaf_a1 = ChequeLeaf.objects.get(bank_account=self.ba_a, cheque_number="002451")
        b2c = c_acct.post(
            "/api/vouchers/contra/",
            {
                "contra_type": "BANK_TO_CASH",
                "voucher_date": self.tx_date.isoformat(),
                "source_bank_account_id": str(self.ba_a.id),
                "cash_account_id": str(self.cash_acc.id),
                "payment_mode": "CHEQUE",
                "cheque_leaf_id": str(leaf_a1.id),
                "amount": "25000.00",
                "submit": True,
            },
            format="json",
        )
        self.assertEqual(b2c.status_code, 201, b2c.content)
        leaf_a1.refresh_from_db()
        self.assertEqual(leaf_a1.status, ChequeLeaf.Status.RESERVED)

        v_b2c_id = b2c.json()["id"]
        c_fin.post(f"/api/vouchers/{v_b2c_id}/approve/")
        post_b2c = c_fin.post(f"/api/vouchers/{v_b2c_id}/post/")
        self.assertEqual(post_b2c.status_code, 200, post_b2c.content)
        leaf_a1.refresh_from_db()
        self.assertEqual(leaf_a1.status, ChequeLeaf.Status.ISSUED)
        self.assertEqual(BankingService.get_gl_balance(self.ba_a.gl_account), Decimal("1075000.00"))
        self.assertEqual(BankingService.get_gl_balance(self.cash_acc.gl_account), Decimal("225000.00"))

        # 11. Bank-to-Bank Contra (identical accounts rejected; Sending Bank cheque works!)
        same_ba = c_acct.post(
            "/api/vouchers/contra/",
            {
                "contra_type": "BANK_TO_BANK",
                "voucher_date": self.tx_date.isoformat(),
                "source_bank_account_id": str(self.ba_a.id),
                "destination_bank_account_id": str(self.ba_a.id),
                "amount": "50000.00",
            },
            format="json",
        )
        self.assertEqual(same_ba.status_code, 400)

        # Reject Destination Bank's cheque under Sending Bank B2B transfer!
        leaf_b1 = ChequeLeaf.objects.get(bank_account=self.ba_b, cheque_number="009001")
        wrong_side_chq = c_acct.post(
            "/api/vouchers/contra/",
            {
                "contra_type": "BANK_TO_BANK",
                "voucher_date": self.tx_date.isoformat(),
                "source_bank_account_id": str(self.ba_a.id),
                "destination_bank_account_id": str(self.ba_b.id),
                "payment_mode": "CHEQUE",
                "cheque_leaf_id": str(leaf_b1.id),
                "amount": "50000.00",
            },
            format="json",
        )
        self.assertEqual(wrong_side_chq.status_code, 400)

        leaf_a2 = ChequeLeaf.objects.get(bank_account=self.ba_a, cheque_number="002452")
        b2b = c_acct.post(
            "/api/vouchers/contra/",
            {
                "contra_type": "BANK_TO_BANK",
                "voucher_date": self.tx_date.isoformat(),
                "source_bank_account_id": str(self.ba_a.id),
                "destination_bank_account_id": str(self.ba_b.id),
                "payment_mode": "CHEQUE",
                "cheque_leaf_id": str(leaf_a2.id),
                "amount": "150000.00",
                "submit": True,
            },
            format="json",
        )
        self.assertEqual(b2b.status_code, 201, b2b.content)
        v_b2b_id = b2b.json()["id"]
        c_fin.post(f"/api/vouchers/{v_b2b_id}/approve/")
        c_fin.post(f"/api/vouchers/{v_b2b_id}/post/")
        self.assertEqual(BankingService.get_gl_balance(self.ba_a.gl_account), Decimal("925000.00"))
        self.assertEqual(BankingService.get_gl_balance(self.ba_b.gl_account), Decimal("400000.00"))

        # Bank-Transfer-In-Transit & Incoming Confirmation workflow
        t1 = c_acct.post(
            "/api/vouchers/contra/",
            {
                "contra_type": "BANK_TRANSFER_IN_TRANSIT",
                "voucher_date": self.tx_date.isoformat(),
                "source_bank_account_id": str(self.ba_a.id),
                "amount": "30000.00",
                "submit": True,
            },
            format="json",
        ).json()
        c_fin.post(f"/api/vouchers/{t1['id']}/approve/")
        c_fin.post(f"/api/vouchers/{t1['id']}/post/")
        it_acc = get_bank_transfer_in_transit_account(self.company)
        self.assertEqual(BankingService.get_gl_balance(it_acc), Decimal("30000.00"))

        t2 = c_acct.post(
            "/api/vouchers/contra/",
            {
                "contra_type": "INCOMING_TRANSFER_CONFIRMATION",
                "voucher_date": self.tx_date.isoformat(),
                "destination_bank_account_id": str(self.ba_b.id),
                "amount": "30000.00",
                "submit": True,
            },
            format="json",
        ).json()
        c_fin.post(f"/api/vouchers/{t2['id']}/approve/")
        c_fin.post(f"/api/vouchers/{t2['id']}/post/")
        self.assertEqual(BankingService.get_gl_balance(it_acc), Decimal("0.00"))

        # 12. External supplier payment remains PAYMENT (Dr Creditors / Cr Bank A)
        leaf_a3 = ChequeLeaf.objects.get(bank_account=self.ba_a, cheque_number="002453")
        pay = c_acct.post(
            "/api/vouchers/payment/",
            {
                "voucher_date": self.tx_date.isoformat(),
                "payment_mode": "CHEQUE",
                "bank_account_id": str(self.ba_a.id),
                "cheque_leaf_id": str(leaf_a3.id),
                "party": str(self.supplier.id),
                "amount": "45000.00",
                "submit": True,
            },
            format="json",
        )
        self.assertEqual(pay.status_code, 201, pay.content)
        pay_data = pay.json()
        self.assertEqual(pay_data["voucher_type"], Voucher.VoucherType.PAYMENT)
        c_fin.post(f"/api/vouchers/{pay_data['id']}/approve/")
        c_fin.post(f"/api/vouchers/{pay_data['id']}/post/")
        leaf_a3.refresh_from_db()
        self.assertEqual(leaf_a3.status, ChequeLeaf.Status.ISSUED)
        self.assertEqual(BankingService.get_gl_balance(self.ba_a.gl_account), Decimal("850000.00"))

        # Contra rejects external party
        bad_contra = c_acct.post(
            "/api/vouchers/contra/",
            {
                "contra_type": "CASH_TO_BANK",
                "voucher_date": self.tx_date.isoformat(),
                "cash_account_id": str(self.cash_acc.id),
                "destination_bank_account_id": str(self.ba_a.id),
                "party": str(self.supplier.id),
                "amount": "5000.00",
            },
            format="json",
        )
        self.assertEqual(bad_contra.status_code, 400)

        # 13 & 14. Reversing posted Payment preserves cheque # (NEVER returns to AVAILABLE!) and keeps GL agreement + audit trail
        rev = c_fin.post(
            f"/api/v1/vouchers/{pay_data['id']}/reverse/",
            {"reversal_date": self.tx_date.isoformat(), "reason": "Wrong bill settled"},
            format="json",
        )
        self.assertEqual(rev.status_code, 201, rev.content)
        leaf_a3.refresh_from_db()
        self.assertEqual(leaf_a3.status, ChequeLeaf.Status.CANCELLED)
        self.assertEqual(leaf_a3.cheque_number, "002453")
        self.assertIsNotNone(leaf_a3.reversal_voucher_id)

        # Book balance agrees with GL Ledger after reversal (850,000 + 45,000 = 895,000)
        ba_a_api = c_fin.get(f"/api/bank-accounts/{self.ba_a.id}/ledger/").json()
        self.assertEqual(Decimal(ba_a_api["bank_account"]["current_balance"]), Decimal("895000.00"))
        self.assertEqual(BankingService.get_gl_balance(self.ba_a.gl_account), Decimal("895000.00"))

        # Bank Transaction Register reflects all entries & running balance
        txns = c_fin.get(f"/api/bank-transactions/?bank_account={self.ba_a.id}").json()["results"]
        self.assertTrue(len(txns) >= 4)
        self.assertTrue(AuditEvent.objects.filter(company=self.company, action="VOUCHER_REVERSED").exists())

