from datetime import date, timedelta
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, LedgerEntry, Party, Voucher
from apps.accounting.services import PostingService, VoucherService
from apps.banking.models import Bank, BankAccount, BankBranch, ChequeBook, ChequeLeaf
from apps.banking.services import BankingService
from apps.localization.bs_calendar import bs_to_ad
from apps.party_hub.models import OpenItem
from apps.projects.models import Project
from apps.tenancy.models import Company, FiscalYear
from apps.treasury.cheques.gl_helpers import (
    get_cheques_in_clearing_account,
    get_cheques_in_hand_account,
)
from apps.treasury.cheques.models import ChequeDepositBatch, ChequeReturn, ChequeReversal
from apps.treasury.cheques.reversals.service import ChequeReversalEngine


class EnterpriseChequeLifecycleTests(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="CHQ1",
            name="Himalaya Construction & Infra Ltd",
            pan_vat_no="609988776",
            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="chq_fin", email="fin@chq.local", password="Password@123")
        self.accountant = User.objects.create_user(username="chq_acct", email="acct@chq.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.accountant, company=self.company, role=self.roles["ACCOUNTANT"], is_default=True)

        self.bank = Bank.objects.create(company=self.company, name="Nabil Bank Ltd", short_code="NABIL")
        self.branch = BankBranch.objects.create(bank=self.bank, branch_code="KTM", name="Kathmandu Main")
        self.ba = BankingService.create_bank_account(
            company=self.company,
            user=self.fin_mgr,
            bank_branch=self.branch,
            account_name="Nabil Current Operating",
            account_number="001122334455",
            account_type="CURRENT",
            purpose="GENERAL",
            currency="NPR",
            opening_balance=Decimal("500000.00"),
        )
        self.debtors_acc = Account.objects.create(
            company=self.company,
            code="1101",
            name="Sundry Debtors Control",
            account_type=Account.AccountType.ASSET,
            control_role=Account.ControlRole.SUNDRY_DEBTORS,
            requires_subledger=True,
            allow_direct_posting=True,
        )
        self.creditors_acc = Account.objects.create(
            company=self.company,
            code="2001",
            name="Sundry Creditors Control",
            account_type=Account.AccountType.LIABILITY,
            control_role=Account.ControlRole.SUNDRY_CREDITORS,
            requires_subledger=True,
            allow_direct_posting=True,
        )
        self.rev_acc = Account.objects.create(
            company=self.company,
            code="4001",
            name="Contract Billing Income",
            account_type=Account.AccountType.INCOME,
            allow_direct_posting=True,
        )
        self.customer = Party.objects.create(
            company=self.company,
            party_type=Party.PartyType.CUSTOMER,
            code="CUST-ABC",
            name="Customer ABC Infra",
            control_account=self.debtors_acc,
        )
        self.supplier = Party.objects.create(
            company=self.company,
            party_type=Party.PartyType.SUPPLIER,
            code="SUP-CEM",
            name="Everest Cement Suppliers",
            control_account=self.creditors_acc,
        )
        self.project = Project.objects.create(
            company=self.company,
            code="PRJ-CHQ",
            name="Ringroad Expansion Phase II",
            start_date=self.tx_date,
        )

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

    def _create_customer_invoice(self, amount=Decimal("100000.00"), ref="INV-001") -> OpenItem:
        v = VoucherService.create_draft(
            company=self.company,
            user=self.fin_mgr,
            data={
                "voucher_type": Voucher.VoucherType.SALES,
                "voucher_date": self.tx_date,
                "party": self.customer,
                "project": self.project,
                "reference_no": ref,
                "narration": f"Sales Invoice {ref}",
                "gross_amount": amount,
                "net_amount": amount,
            },
            lines_data=[
                {"account": self.debtors_acc, "party": self.customer, "debit": amount, "credit": Decimal("0.00"), "project": self.project},
                {"account": self.rev_acc, "debit": Decimal("0.00"), "credit": amount, "project": self.project},
            ],
        )
        v.status = Voucher.Status.APPROVED
        v.save()
        v = PostingService.post_voucher(voucher=v, user=self.fin_mgr)
        return OpenItem.objects.get(company=self.company, voucher=v, party=self.customer, is_unallocated_credit=False)

    def test_01_cheque_book_leaves_overlap_duplicate_and_cancelled_reuse_block(self):
        c = self._client(self.fin_mgr)
        # Register cheque book 1001..1005
        res = c.post(
            "/api/v1/cheques/books/",
            {
                "bank_account": str(self.ba.id),
                "book_code": "BK-01",
                "prefix": "NB-",
                "start_number": 1001,
                "end_number": 1005,
                "issued_date": self.tx_date.isoformat(),
            },
            format="json",
        )
        self.assertEqual(res.status_code, 201, res.content)
        book_id = res.json()["id"]
        self.assertEqual(res.json()["total_leaves"], 5)
        self.assertEqual(ChequeLeaf.objects.filter(cheque_book_id=book_id).count(), 5)

        # Overlapping active range rejected
        overlap = c.post(
            "/api/v1/cheques/books/",
            {
                "bank_account": str(self.ba.id),
                "book_code": "BK-OVERLAP",
                "prefix": "NB-",
                "start_number": 1004,
                "end_number": 1010,
                "issued_date": self.tx_date.isoformat(),
            },
            format="json",
        )
        self.assertEqual(overlap.status_code, 400)

        # Issue cheque leaf NB-1001
        leaves = c.get(f"/api/v1/cheques/books/{book_id}/leaves/").json()
        leaf_1001 = leaves[0]["id"]
        leaf_1002 = leaves[1]["id"]

        iss = c.post(
            "/api/v1/cheques/issued/",
            {
                "bank_account": str(self.ba.id),
                "cheque_leaf": leaf_1001,
                "party": str(self.supplier.id),
                "payee_name": self.supplier.name,
                "amount": "50000.00",
                "cheque_date": self.tx_date.isoformat(),
            },
            format="json",
        )
        self.assertEqual(iss.status_code, 201, iss.content)

        # Same issued cheque number entered twice -> rejected
        dup_iss = c.post(
            "/api/v1/cheques/issued/",
            {
                "bank_account": str(self.ba.id),
                "cheque_number": "NB-1001",
                "payee_name": self.supplier.name,
                "amount": "50000.00",
                "cheque_date": self.tx_date.isoformat(),
            },
            format="json",
        )
        self.assertEqual(dup_iss.status_code, 400)

        # Cancel leaf NB-1002 -> cannot be reused
        sk = c.post(f"/api/v1/cheques/leaves/{leaf_1002}/damage/", {"reason": "Torn leaf", "kind": "LOST_DAMAGED"}, format="json")
        self.assertEqual(sk.status_code, 200)
        reuse = c.post(
            "/api/v1/cheques/issued/",
            {
                "bank_account": str(self.ba.id),
                "cheque_leaf": leaf_1002,
                "payee_name": "Test",
                "amount": "1000.00",
                "cheque_date": self.tx_date.isoformat(),
            },
            format="json",
        )
        self.assertEqual(reuse.status_code, 400)

    def test_02_two_step_received_cheque_clearing_and_gl_subledger_reconciliation(self):
        c = self._client(self.fin_mgr)
        inv = self._create_customer_invoice(Decimal("100000.00"), "RA-100")

        # Stage 0: Receive NPR 100,000 customer cheque allocated to invoice RA-100
        rc = c.post(
            "/api/v1/cheques/received/",
            {
                "bank_account": str(self.ba.id),
                "cheque_number": "005544",
                "customer": str(self.customer.id),
                "drawer_name": self.customer.name,
                "drawer_bank": "Rastriya Banijya Bank",
                "drawer_account_ref": "112233445566",
                "amount": "100000.00",
                "cheque_date": self.tx_date.isoformat(),
                "received_date": self.tx_date.isoformat(),
                "project": str(self.project.id),
                "allocations": [{"open_item_id": str(inv.id), "allocated_amount": "100000.00"}],
            },
            format="json",
        )
        self.assertEqual(rc.status_code, 201, rc.content)
        rc_data = rc.json()
        leaf_id = rc_data["leaf"]
        self.assertEqual(rc_data["drawer_account_masked"], "********5566")

        cih_acc = get_cheques_in_hand_account(self.company)
        cic_acc = get_cheques_in_clearing_account(self.company)

        # Verify Stage 0 balances:
        # 1035 Cheques-in-Hand = 100,000; 1036 Cheques-in-Clearing = 0; Bank GL unchanged (500,000); Invoice settled
        self.assertEqual(BankingService.get_gl_balance(cih_acc), Decimal("100000.00"))
        self.assertEqual(BankingService.get_gl_balance(cic_acc), Decimal("0.00"))
        self.assertEqual(BankingService.get_gl_balance(self.ba.gl_account), Decimal("500000.00"))
        inv.refresh_from_db()
        self.assertEqual(inv.status, OpenItem.Status.SETTLED)

        # Cannot jump straight to clearing confirmation without Step 1 deposit!
        premature = c.post(f"/api/v1/cheques/{leaf_id}/confirm-clearing/", {}, format="json")
        self.assertEqual(premature.status_code, 400)

        # Step 1: Deposit -> Dr Cheques-in-Clearing (1036) / Cr Cheques-in-Hand (1035)
        self.assertEqual(c.post(f"/api/v1/cheques/{leaf_id}/verify/", {}, format="json").status_code, 200)
        dep = c.post(
            f"/api/v1/cheques/{leaf_id}/deposit/",
            {"deposit_slip_no": "SLIP-889", "deposit_date": self.tx_date.isoformat()},
            format="json",
        )
        self.assertEqual(dep.status_code, 200, dep.content)
        self.assertEqual(BankingService.get_gl_balance(cih_acc), Decimal("0.00"))
        self.assertEqual(BankingService.get_gl_balance(cic_acc), Decimal("100000.00"))
        self.assertEqual(BankingService.get_gl_balance(self.ba.gl_account), Decimal("500000.00"))

        # GL == Subledger check during clearing
        recon = ChequeReversalEngine.reconcile_subledger_with_gl(company=self.company)
        self.assertTrue(recon["cheques_in_hand"]["reconciled"])
        self.assertTrue(recon["cheques_in_clearing"]["reconciled"])

        # Step 2: Confirm Bank Clearance -> Dr Bank GL / Cr Cheques-in-Clearing (1036)
        clr = c.post(
            f"/api/v1/cheques/{leaf_id}/confirm-clearing/",
            {"cleared_date": self.tx_date.isoformat(), "bank_reference": "CLR-NABIL-99"},
            format="json",
        )
        self.assertEqual(clr.status_code, 200, clr.content)
        self.assertEqual(BankingService.get_gl_balance(cih_acc), Decimal("0.00"))
        self.assertEqual(BankingService.get_gl_balance(cic_acc), Decimal("0.00"))
        self.assertEqual(BankingService.get_gl_balance(self.ba.gl_account), Decimal("600000.00"))

        # GL == Subledger final verification
        recon_final = ChequeReversalEngine.reconcile_subledger_with_gl(company=self.company)
        self.assertTrue(recon_final["cheques_in_hand"]["reconciled"])
        self.assertTrue(recon_final["cheques_in_clearing"]["reconciled"])

    def test_03_bounce_scenarios_a_b_c_with_invoice_reopening_and_bank_charge(self):
        c = self._client(self.fin_mgr)
        cih_acc = get_cheques_in_hand_account(self.company)
        cic_acc = get_cheques_in_clearing_account(self.company)

        # Scenario A: Bounce before deposit restores Customer Invoice OpenItem cleanly
        inv_a = self._create_customer_invoice(Decimal("40000.00"), "INV-A")
        rc_a = c.post(
            "/api/v1/cheques/received/",
            {
                "bank_account": str(self.ba.id),
                "cheque_number": "77001",
                "customer": str(self.customer.id),
                "drawer_name": self.customer.name,
                "drawer_bank": "Global IME",
                "drawer_account_ref": "ACC-A",
                "amount": "40000.00",
                "cheque_date": self.tx_date.isoformat(),
                "allocations": [{"open_item_id": str(inv_a.id), "allocated_amount": "40000.00"}],
            },
            format="json",
        ).json()
        inv_a.refresh_from_db()
        self.assertEqual(inv_a.status, OpenItem.Status.SETTLED)

        b_a = c.post(
            f"/api/v1/cheques/{rc_a['leaf']}/bounce/",
            {"bounce_date": self.tx_date.isoformat(), "return_reason": "Post-dated cancelled by drawer"},
            format="json",
        )
        self.assertEqual(b_a.status_code, 200, b_a.content)
        self.assertEqual(b_a.json()["bounce_scenario"], ChequeReturn.BounceScenario.BEFORE_DEPOSIT)
        inv_a.refresh_from_db()
        self.assertEqual(inv_a.status, OpenItem.Status.OPEN)
        self.assertEqual(inv_a.remaining_amount, Decimal("40000.00"))
        self.assertEqual(BankingService.get_gl_balance(cih_acc), Decimal("0.00"))

        # Scenario B: Bounce after deposit, before clearance -> 2 linked reversals + reopened invoice
        inv_b = self._create_customer_invoice(Decimal("60000.00"), "INV-B")
        rc_b = c.post(
            "/api/v1/cheques/received/",
            {
                "bank_account": str(self.ba.id),
                "cheque_number": "77002",
                "customer": str(self.customer.id),
                "drawer_name": self.customer.name,
                "drawer_bank": "Global IME",
                "drawer_account_ref": "ACC-B",
                "amount": "60000.00",
                "cheque_date": self.tx_date.isoformat(),
                "allocations": [{"open_item_id": str(inv_b.id), "allocated_amount": "60000.00"}],
            },
            format="json",
        ).json()
        c.post(f"/api/v1/cheques/{rc_b['leaf']}/deposit/", {"deposit_slip_no": "SLIP-B"}, format="json")
        self.assertEqual(BankingService.get_gl_balance(cic_acc), Decimal("60000.00"))

        b_b = c.post(
            f"/api/v1/cheques/{rc_b['leaf']}/bounce/",
            {"bounce_date": self.tx_date.isoformat(), "return_reason": "Insufficient funds", "bank_charge_amount": "500.00"},
            format="json",
        )
        self.assertEqual(b_b.status_code, 200, b_b.content)
        bb_data = b_b.json()
        self.assertEqual(bb_data["bounce_scenario"], ChequeReturn.BounceScenario.AFTER_DEPOSIT)
        steps = {r["step_kind"] for r in bb_data["reversals"]}
        self.assertSetEqual(
            steps,
            {
                ChequeReversal.StepKind.DEPOSIT_TRANSFER_REVERSAL,
                ChequeReversal.StepKind.RECEIPT_REVERSAL,
                ChequeReversal.StepKind.BANK_CHARGE,
            },
        )
        inv_b.refresh_from_db()
        self.assertEqual(inv_b.status, OpenItem.Status.OPEN)
        self.assertEqual(BankingService.get_gl_balance(cih_acc), Decimal("0.00"))
        self.assertEqual(BankingService.get_gl_balance(cic_acc), Decimal("0.00"))
        # Bank balance reduced strictly by 500 return fee
        self.assertEqual(BankingService.get_gl_balance(self.ba.gl_account), Decimal("499500.00"))

        # Scenario C: Bounce after bank credit -> reverses Bank credit, restores Debtors & logs fee
        inv_c = self._create_customer_invoice(Decimal("25000.00"), "INV-C")
        rc_c = c.post(
            "/api/v1/cheques/received/",
            {
                "bank_account": str(self.ba.id),
                "cheque_number": "77003",
                "customer": str(self.customer.id),
                "drawer_name": self.customer.name,
                "drawer_bank": "Sanima Bank",
                "drawer_account_ref": "ACC-C",
                "amount": "25000.00",
                "cheque_date": self.tx_date.isoformat(),
                "allocations": [{"open_item_id": str(inv_c.id), "allocated_amount": "25000.00"}],
            },
            format="json",
        ).json()
        c.post(f"/api/v1/cheques/{rc_c['leaf']}/deposit/", {"deposit_slip_no": "SLIP-C"}, format="json")
        c.post(f"/api/v1/cheques/{rc_c['leaf']}/confirm-clearing/", {"bank_reference": "CLR-C"}, format="json")
        self.assertEqual(BankingService.get_gl_balance(self.ba.gl_account), Decimal("524500.00"))

        b_c = c.post(
            f"/api/v1/cheques/{rc_c['leaf']}/bounce/",
            {"bounce_date": self.tx_date.isoformat(), "return_reason": "Clearing recall", "bank_charge_amount": "300.00"},
            format="json",
        )
        self.assertEqual(b_c.status_code, 200, b_c.content)
        self.assertEqual(b_c.json()["bounce_scenario"], ChequeReturn.BounceScenario.AFTER_CLEARANCE)
        # Bank returns 25,000 + 300 charge -> 524,500 - 25,300 = 499,200
        self.assertEqual(BankingService.get_gl_balance(self.ba.gl_account), Decimal("499200.00"))
        inv_c.refresh_from_db()
        self.assertEqual(inv_c.status, OpenItem.Status.OPEN)

    def test_04_partial_deposit_batch_statement_idempotency_and_replacement(self):
        c = self._client(self.fin_mgr)
        c_acct = self._client(self.accountant)

        # Receive 3 customer cheques
        c_ids = []
        for idx in range(1, 4):
            r = c_acct.post(
                "/api/v1/cheques/received/",
                {
                    "bank_account": str(self.ba.id),
                    "cheque_number": f"8800{idx}",
                    "customer": str(self.customer.id),
                    "drawer_name": self.customer.name,
                    "drawer_bank": "NIC Asia",
                    "drawer_account_ref": f"NIC-{idx}",
                    "amount": "10000.00",
                    "cheque_date": self.tx_date.isoformat(),
                },
                format="json",
            )
            self.assertEqual(r.status_code, 201)
            c_ids.append(r.json()["leaf"])

        # Create Deposit Batch containing all 3 cheques (30,000 total)
        batch = c_acct.post(
            "/api/v1/cheques/deposit-batches/",
            {
                "bank_account": str(self.ba.id),
                "cheque_ids": c_ids,
                "deposit_slip_no": "BATCH-SLIP-1",
                "deposit_date": self.tx_date.isoformat(),
            },
            format="json",
        )
        self.assertEqual(batch.status_code, 201, batch.content)
        b_data = batch.json()
        self.assertEqual(b_data["status"], ChequeDepositBatch.Status.DEPOSITED)
        cic_acc = get_cheques_in_clearing_account(self.company)
        self.assertEqual(BankingService.get_gl_balance(cic_acc), Decimal("30000.00"))

        # Clear ONLY line 1 (c_ids[0] = 88001) -> batch becomes PARTIAL_CLEARED; 88002 and 88003 remain UNDER_CLEARING
        line1_id = next(ln["id"] for ln in b_data["lines"] if ln["cheque_leaf"] == c_ids[0])
        line2_id = next(ln["id"] for ln in b_data["lines"] if ln["cheque_leaf"] == c_ids[1])
        clr_res = c.post(f"/api/v1/cheques/deposit-batches/{b_data['id']}/clear-line/", {"line_id": line1_id}, format="json")
        self.assertEqual(clr_res.status_code, 200)
        self.assertEqual(clr_res.json()["status"], ChequeDepositBatch.Status.PARTIAL_CLEARED)
        self.assertEqual(BankingService.get_gl_balance(cic_acc), Decimal("20000.00"))
        self.assertEqual(BankingService.get_gl_balance(self.ba.gl_account), Decimal("510000.00"))

        # Return ONLY line 2 -> line 3 stays UNDER_CLEARING!
        ret_res = c.post(
            f"/api/v1/cheques/deposit-batches/{b_data['id']}/return-line/",
            {"line_id": line2_id, "return_reason": "Signature differs"},
            format="json",
        )
        self.assertEqual(ret_res.status_code, 200, ret_res.content)
        self.assertEqual(ret_res.json()["status"], ChequeDepositBatch.Status.PARTIAL_BOUNCED)
        self.assertEqual(BankingService.get_gl_balance(cic_acc), Decimal("10000.00"))

        # Re-importing / attempting duplicate clear on line 1 is blocked cleanly
        dup_clear = c.post(f"/api/v1/cheques/{c_ids[0]}/confirm-clearing/", {}, format="json")
        self.assertEqual(dup_clear.status_code, 400)

        # Replace bounced cheque #2 with new cheque
        repl = c.post(
            f"/api/v1/cheques/{c_ids[1]}/replace/",
            {"new_cheque_number": "88099", "reason": "Reissued by Customer ABC"},
            format="json",
        )
        self.assertEqual(repl.status_code, 201, repl.content)
        self.assertEqual(repl.json()["original_cheque_number"], "88002")
        self.assertEqual(repl.json()["replacement_cheque_number"], "88099")

        # Verify Statement Import idempotency with Cheque Clearing Match
        csv_bytes = (
            "Date,Reference,Cheque,Description,Debit,Credit,Balance\n"
            f"{self.tx_date.isoformat()},CLR-88003,88003,NIC Clearing Deposit 88003,0.00,10000.00,520000.00\n"
        ).encode("utf-8")
        BankingService.import_statement(
            company=self.company, user=self.fin_mgr, bank_account=self.ba, file_name="s1.csv", file_format="CSV", content_bytes=csv_bytes
        )
        imp2 = BankingService.import_statement(
            company=self.company, user=self.fin_mgr, bank_account=self.ba, file_name="s2.csv", file_format="CSV", content_bytes=csv_bytes
        )
        self.assertEqual(imp2.skipped_duplicates, 1)

        sugg = c.get("/api/v1/cheques/clearing-workbench/").json()
        self.assertTrue(len(sugg) >= 1)
        stmt_id = sugg[0]["statement_line_id"]
        match_confirm = c.post(
            "/api/v1/cheques/clearing-workbench/",
            {"cheque_id": c_ids[2], "statement_line_id": stmt_id},
            format="json",
        )
        self.assertEqual(match_confirm.status_code, 200, match_confirm.content)
        self.assertEqual(BankingService.get_gl_balance(cic_acc), Decimal("0.00"))
        self.assertEqual(BankingService.get_gl_balance(self.ba.gl_account), Decimal("520000.00"))

        # Check all 14 report exports + dashboard endpoint work cleanly
        dash = c.get("/api/v1/cheques/dashboard/")
        self.assertEqual(dash.status_code, 200)
        rpt_csv = c.get("/api/v1/cheques/reports/?report_type=RECEIVED_CHEQUE_REGISTER&export_format=csv")
        self.assertEqual(rpt_csv.status_code, 200)
        self.assertIn(b"88001", rpt_csv.content)
        rpt_xlsx = c.get("/api/v1/cheques/reports/?report_type=DEPOSIT_BATCH_REGISTER&export_format=xlsx")
        self.assertEqual(rpt_xlsx.status_code, 200)

