from datetime import timedelta
from decimal import Decimal
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase
from rest_framework.test import APIClient

from apps.accounts_rbac.constants import Permissions, ROLE_PRESETS
from apps.accounts_rbac.models import ApprovalAuthority, CompanyMembership, Role, User
from apps.accounting.models import (
    Account,
    LedgerEntry,
    Party,
    Voucher,
    VoucherAttachment,
    VoucherRegisterViewConfig,
)
from apps.accounting.services import ApprovalService, PostingService, VoucherService
from apps.audit.models import AuditEvent
from apps.localization.bs_calendar import bs_to_ad
from apps.projects.models import Project, Site
from apps.tenancy.models import Branch, Company, FiscalYear, TaxConfig


class EnterpriseVoucherRegisterTests(TestCase):
    def setUp(self):
        self.roles = {
            code: Role.objects.create(code=code, name=spec["name"], permissions=spec["permissions"])
            for code, spec in ROLE_PRESETS.items()
        }
        self.admin = User.objects.create_user(username="reg_admin", email="reg_admin@test.local", password="Password@123")
        self.accountant = User.objects.create_user(username="reg_acc", email="reg_acc@test.local", password="Password@123")
        self.finance = User.objects.create_user(username="reg_fin", email="reg_fin@test.local", password="Password@123")
        self.supervisor = User.objects.create_user(username="reg_sup", email="reg_sup@test.local", password="Password@123")

        self.company = Company.objects.create(
            code="VREG", name="Himalayan Register Test Corp", pan_vat_no="601112223", base_currency="NPR"
        )
        self.other_company = Company.objects.create(
            code="OTHR", name="Other Tenant Co", pan_vat_no="609998887", base_currency="NPR"
        )
        self.branch = Branch.objects.create(company=self.company, code="HO", name="Head Office", is_head_office=True)

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

        self.project_a = Project.objects.create(company=self.company, code="PRJ-A", name="Bridge Project A", budget_amount=Decimal("1000000.00"))
        self.project_b = Project.objects.create(company=self.company, code="PRJ-B", name="Road Project B", budget_amount=Decimal("1000000.00"))
        self.site_a = Site.objects.create(project=self.project_a, code="SITE-A1", name="Pier 1", location="Kathmandu")

        sup_membership = CompanyMembership.objects.create(
            user=self.supervisor,
            company=self.company,
            role=self.roles["SITE_SUPERVISOR"],
            data_scope=CompanyMembership.DataScope.PROJECT,
            is_default=True,
        )
        sup_membership.projects.add(self.project_a)

        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.v_date = bs_to_ad(2083, 4, 20)

        self.acc_bank = Account.objects.create(
            company=self.company, code="10201", name="Nabil Bank", account_type=Account.AccountType.ASSET,
            control_role=Account.ControlRole.BANK, allow_direct_posting=True,
        )
        self.acc_exp = Account.objects.create(
            company=self.company, code="50101", name="Construction Material", account_type=Account.AccountType.EXPENSE,
            control_role=Account.ControlRole.DIRECT_EXPENSES, allow_direct_posting=True,
        )
        self.acc_ap = Account.objects.create(
            company=self.company, code="20101", name="Sundry Creditors", account_type=Account.AccountType.LIABILITY,
            control_role=Account.ControlRole.SUNDRY_CREDITORS, requires_subledger=True, is_control_account=True, allow_direct_posting=True,
        )
        self.acc_vat_in = Account.objects.create(
            company=self.company, code="12501", name="Input VAT", account_type=Account.AccountType.ASSET,
            control_role=Account.ControlRole.INPUT_VAT, allow_direct_posting=True,
        )
        self.acc_tds = Account.objects.create(
            company=self.company, code="20501", name="TDS Payable", account_type=Account.AccountType.LIABILITY,
            control_role=Account.ControlRole.TDS_PAYABLE, allow_direct_posting=True,
        )

        self.tax_vat = TaxConfig.objects.create(
            company=self.company,
            code="VAT13",
            name="Standard Nepal VAT 13%",
            tax_type=TaxConfig.TaxType.VAT,
            rate=Decimal("13.00"),
            effective_from=self.v_date - timedelta(days=30),
            category="STANDARD_VAT",
            calculation_rule="13% on taxable base",
            tax_ledger=self.acc_vat_in,
        )
        self.tax_tds = TaxConfig.objects.create(
            company=self.company,
            code="TDS15",
            name="Contract TDS 1.5%",
            tax_type=TaxConfig.TaxType.TDS,
            rate=Decimal("1.50"),
            effective_from=self.v_date - timedelta(days=30),
            category="CONTRACT_TDS",
            calculation_rule="1.5% Sec 89 TDS",
            tax_ledger=self.acc_tds,
        )

        self.supplier = Party.objects.create(
            company=self.company, party_type=Party.PartyType.SUPPLIER, code="SUP-01",
            name="ABC Building Materials", pan_vat_no="602223334", control_account=self.acc_ap,
        )

        # Voucher 1: Posted Purchase Voucher on Project A (with VAT + TDS)
        self.v_posted = VoucherService.create_draft(
            company=self.company,
            user=self.accountant,
            data={
                "voucher_type": Voucher.VoucherType.PURCHASE,
                "voucher_date": self.v_date,
                "branch": self.branch,
                "project": self.project_a,
                "site": self.site_a,
                "party": self.supplier,
                "supplier_invoice_no": "SUP-INV-100",
                "reference_no": "BILL-100",
                "narration": "Cement and TMT Steel purchase for Pier 1",
                "gross_amount": Decimal("100000.00"),
                "tax_amount": Decimal("13000.00"),
                "tds_amount": Decimal("1500.00"),
                "net_amount": Decimal("111500.00"),
            },
            lines_data=[
                {"account": self.acc_exp, "debit": Decimal("100000.00"), "credit": Decimal("0.00"), "project": self.project_a},
                {"account": self.acc_vat_in, "debit": Decimal("13000.00"), "credit": Decimal("0.00"), "project": self.project_a},
                {"account": self.acc_tds, "debit": Decimal("0.00"), "credit": Decimal("1500.00")},
                {"account": self.acc_ap, "party": self.supplier, "debit": Decimal("0.00"), "credit": Decimal("111500.00"), "project": self.project_a},
            ],
        )
        VoucherService.submit_voucher(voucher=self.v_posted, user=self.accountant)
        ApprovalService.approve_voucher(voucher=self.v_posted, user=self.finance, comment="Verified invoice")
        PostingService.post_voucher(voucher=self.v_posted, user=self.finance)

        # Voucher 2: Submitted Payment Voucher on Project B (for scope & bulk tests)
        self.v_submitted = VoucherService.create_draft(
            company=self.company,
            user=self.accountant,
            data={
                "voucher_type": Voucher.VoucherType.PAYMENT,
                "voucher_date": self.v_date,
                "branch": self.branch,
                "project": self.project_b,
                "party": self.supplier,
                "reference_no": "PAY-200",
                "narration": "Advance payment for Road Project B",
                "gross_amount": Decimal("50000.00"),
                "net_amount": Decimal("50000.00"),
            },
            lines_data=[
                {"account": self.acc_ap, "party": self.supplier, "debit": Decimal("50000.00"), "credit": Decimal("0.00"), "project": self.project_b},
                {"account": self.acc_bank, "debit": Decimal("0.00"), "credit": Decimal("50000.00"), "project": self.project_b},
            ],
        )
        VoucherService.submit_voucher(voucher=self.v_submitted, user=self.accountant)

        # Voucher 3: Draft Journal Voucher on Project A
        self.v_draft = VoucherService.create_draft(
            company=self.company,
            user=self.accountant,
            data={
                "voucher_type": Voucher.VoucherType.JOURNAL,
                "voucher_date": self.v_date,
                "project": self.project_a,
                "reference_no": "ADJ-300",
                "narration": "Draft site overhead accrual",
            },
            lines_data=[
                {"account": self.acc_exp, "debit": Decimal("12000.00"), "credit": Decimal("0.00"), "project": self.project_a},
                {"account": self.acc_bank, "debit": Decimal("0.00"), "credit": Decimal("12000.00"), "project": self.project_a},
            ],
        )

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

    def test_register_filtering_sorting_totals_and_scope_isolation(self):
        fin_client = self._client(self.finance)
        res = fin_client.get("/api/v1/vouchers/?view=register&page_size=25")
        self.assertEqual(res.status_code, 200)
        self.assertEqual(res.data["count"], 3)
        self.assertEqual(Decimal(res.data["summary"]["total_debit"]), Decimal("175000.00"))
        self.assertEqual(Decimal(res.data["summary"]["total_credit"]), Decimal("175000.00"))

        # Scope filter: PURCHASE register
        pur = fin_client.get("/api/v1/vouchers/?view=register&register_scope=PURCHASE")
        self.assertEqual(pur.status_code, 200)
        self.assertEqual(pur.data["count"], 1)
        self.assertEqual(pur.data["results"][0]["id"], str(self.v_posted.id))

        # Advanced AND/OR conditions
        cond = fin_client.get(
            '/api/v1/vouchers/?view=register&logic_operator=OR&conditions=[{"field":"reference_no","operator":"eq","value":"PAY-200"},{"field":"reference_no","operator":"eq","value":"ADJ-300"}]'
        )
        self.assertEqual(cond.status_code, 200)
        self.assertEqual(cond.data["count"], 2)

        # Project data-scope enforcement: supervisor only sees Project A (v_posted, v_draft), NOT Project B
        sup_client = self._client(self.supervisor)
        sup_res = sup_client.get("/api/v1/vouchers/?view=register")
        self.assertEqual(sup_res.status_code, 200)
        ids = {r["id"] for r in sup_res.data["results"]}
        self.assertIn(str(self.v_posted.id), ids)
        self.assertIn(str(self.v_draft.id), ids)
        self.assertNotIn(str(self.v_submitted.id), ids)

        # Direct ID probe across project scope is blocked
        blocked = sup_client.get(f"/api/v1/vouchers/{self.v_submitted.id}/logic/")
        self.assertEqual(blocked.status_code, 404)

        # Cross-company isolation
        other_res = self._client(self.admin, self.other_company).get("/api/v1/vouchers/?view=register")
        self.assertEqual(other_res.status_code, 403)

    def test_six_inspector_tabs_real_data_and_no_unintended_posting(self):
        fin_client = self._client(self.finance)
        before_gl_count = LedgerEntry.objects.count()
        before_vch_count = Voucher.objects.count()

        # 1. Logic tab: posted vs unposted draft
        logic_posted = fin_client.get(f"/api/v1/vouchers/{self.v_posted.id}/logic/")
        self.assertEqual(logic_posted.status_code, 200)
        self.assertEqual(logic_posted.data["posting_state"], "ACTUAL_POSTED")
        self.assertTrue(logic_posted.data["is_posted"])
        self.assertTrue(logic_posted.data["is_balanced"])
        self.assertEqual(Decimal(logic_posted.data["total_debit"]), Decimal("113000.00"))
        self.assertEqual(logic_posted.data["gl_posting_reference"]["ledger_entry_count"], 4)

        logic_draft = fin_client.get(f"/api/v1/vouchers/{self.v_draft.id}/logic/")
        self.assertEqual(logic_draft.status_code, 200)
        self.assertEqual(logic_draft.data["posting_state"], "UNPOSTED_DRAFT")
        self.assertFalse(logic_draft.data["is_posted"])

        # 2. Tax tab: reconciles with VAT + TDS ledger entries and effective TaxConfig
        tax_res = fin_client.get(f"/api/v1/vouchers/{self.v_posted.id}/tax/")
        self.assertEqual(tax_res.status_code, 200)
        self.assertEqual(Decimal(tax_res.data["summary"]["input_vat"]), Decimal("13000.00"))
        self.assertEqual(Decimal(tax_res.data["summary"]["tds_deduction"]), Decimal("1500.00"))
        self.assertEqual(len(tax_res.data["tax_lines"]), 2)
        self.assertEqual(len(tax_res.data["effective_rules"]), 2)

        # 3. Attachments tab: upload on draft, replace on draft, immutable on posted
        acc_client = self._client(self.accountant)
        pdf_file = SimpleUploadedFile("bill.pdf", b"%PDF-1.4 test content", content_type="application/pdf")
        up_draft = acc_client.post(
            f"/api/v1/vouchers/{self.v_draft.id}/attachments/",
            {"category": "SUPPLIER_BILL", "title": "Site Overhead Memo", "file": pdf_file},
            format="multipart",
        )
        self.assertEqual(up_draft.status_code, 201)
        att_id = up_draft.data["id"]

        dl = acc_client.get(f"/api/v1/vouchers/{self.v_draft.id}/attachments/{att_id}/download/")
        self.assertEqual(dl.status_code, 200)
        self.assertIn(b"%PDF-1.4", b"".join(dl.streaming_content))

        pdf_v2 = SimpleUploadedFile("bill_v2.pdf", b"%PDF-1.4 updated", content_type="application/pdf")
        rep = acc_client.post(
            f"/api/v1/vouchers/{self.v_draft.id}/attachments/{att_id}/replace/",
            {"file": pdf_v2, "notes": "Updated scan"},
            format="multipart",
        )
        self.assertEqual(rep.status_code, 201)
        self.assertEqual(rep.data["version"], 2)

        # Posted voucher attachment cannot be deleted
        up_posted = acc_client.post(
            f"/api/v1/vouchers/{self.v_posted.id}/attachments/",
            {"category": "PDF_INVOICE", "title": "Original Invoice", "file_name": "orig.pdf"},
            format="json",
        )
        self.assertEqual(up_posted.status_code, 201)
        del_posted = acc_client.delete(
            f"/api/v1/vouchers/{self.v_posted.id}/attachments/{up_posted.data['id']}/"
        )
        self.assertEqual(del_posted.status_code, 400)

        # 4. Approvals tab
        app_res = fin_client.get(f"/api/v1/vouchers/{self.v_submitted.id}/approvals/")
        self.assertEqual(app_res.status_code, 200)
        self.assertIn("approve", app_res.data["available_actions"])
        # Maker (accountant) cannot see approve action
        acc_app = acc_client.get(f"/api/v1/vouchers/{self.v_submitted.id}/approvals/")
        self.assertNotIn("approve", acc_app.data["available_actions"])

        # 5. Audit tab: immutable events
        aud_res = fin_client.get(f"/api/v1/vouchers/{self.v_posted.id}/audit/")
        self.assertEqual(aud_res.status_code, 200)
        self.assertTrue(aud_res.data["is_immutable"])
        self.assertGreaterEqual(len(aud_res.data["events"]), 3)
        ev_obj = AuditEvent.objects.filter(entity_type="Voucher", entity_id=str(self.v_posted.id)).first()
        with self.assertRaises(PermissionError):
            ev_obj.delete()

        # 6. Print Preview tab
        pr_res = fin_client.get(f"/api/v1/vouchers/{self.v_posted.id}/print-preview/")
        self.assertEqual(pr_res.status_code, 200)
        self.assertIn("<html", pr_res.data["html"].lower())
        self.assertTrue(pr_res.data["is_posted"])

        # Confirm zero unintended postings or vouchers were created by inspecting
        self.assertEqual(LedgerEntry.objects.count(), before_gl_count)
        self.assertEqual(Voucher.objects.count(), before_vch_count)

    def test_bulk_approve_authority_export_batch_print_and_saved_views(self):
        # Configure ApprovalAuthority limiting FINANCE_MANAGER to 40,000 -> v_submitted (50,000) exceeds it
        ApprovalAuthority.objects.create(
            company=self.company,
            role=self.roles["FINANCE_MANAGER"],
            voucher_type="ALL",
            min_amount=Decimal("0.00"),
            max_amount=Decimal("40000.00"),
            approval_level=1,
        )
        fin_client = self._client(self.finance)
        bulk_fail = fin_client.post(
            "/api/v1/vouchers/bulk-approve/",
            {"voucher_ids": [str(self.v_submitted.id)]},
            format="json",
        )
        self.assertEqual(bulk_fail.status_code, 200)
        self.assertEqual(len(bulk_fail.data["approved"]), 0)
        self.assertEqual(len(bulk_fail.data["skipped"]), 1)

        # Admin (superuser/company admin with no limit or matching authority)
        ApprovalAuthority.objects.create(
            company=self.company,
            role=self.roles["COMPANY_ADMIN"],
            voucher_type="ALL",
            min_amount=Decimal("0.00"),
            max_amount=Decimal("500000.00"),
            approval_level=2,
        )
        adm_client = self._client(self.admin)
        bulk_ok = adm_client.post(
            "/api/v1/vouchers/bulk-approve/",
            {"voucher_ids": [str(self.v_submitted.id)], "comment": "Authorized"},
            format="json",
        )
        self.assertEqual(bulk_ok.status_code, 200)
        self.assertEqual(len(bulk_ok.data["approved"]), 1)

        # Export CSV & XLSX
        csv_res = adm_client.post("/api/v1/vouchers/export/", {"format": "CSV"}, format="json")
        self.assertEqual(csv_res.status_code, 200)
        self.assertIn(b"SUP-INV-100", csv_res.content)

        xlsx_res = adm_client.post("/api/v1/vouchers/export/", {"format": "XLSX"}, format="json")
        self.assertEqual(xlsx_res.status_code, 200)
        self.assertGreater(len(xlsx_res.content), 500)

        # Batch print
        bp_res = adm_client.post(
            "/api/v1/vouchers/batch-print/",
            {"voucher_ids": [str(self.v_posted.id)], "document_type": "PURCHASE_INVOICE"},
            format="json",
        )
        self.assertEqual(bp_res.status_code, 202)
        self.assertEqual(bp_res.data["total_items"], 1)

        # Saved views CRUD + system protection
        views_res = fin_client.get("/api/v1/voucher-register/views/")
        self.assertEqual(views_res.status_code, 200)
        self.assertGreaterEqual(len(views_res.data["results"]), 11)
        sys_view = next(v for v in views_res.data["results"] if v["is_system"])
        del_sys = fin_client.delete(f"/api/v1/voucher-register/views/{sys_view['id']}/")
        self.assertEqual(del_sys.status_code, 400)

        custom = fin_client.post(
            "/api/v1/voucher-register/views/",
            {"name": "My Construction View", "register_scope": "CONSTRUCTION", "style_code": "CONSTRUCTION_PROJECT"},
            format="json",
        )
        self.assertEqual(custom.status_code, 201)
        upd = fin_client.put(
            f"/api/v1/voucher-register/views/{custom.data['id']}/",
            {"name": "Updated Construction View", "register_scope": "CONSTRUCTION", "style_code": "TALLY_CLASSIC"},
            format="json",
        )
        self.assertEqual(upd.status_code, 200)
        self.assertEqual(upd.data["style_code"], "TALLY_CLASSIC")

