from datetime import date
from decimal import Decimal
from django.core.exceptions import ValidationError
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, Device, Role, User
from apps.accounting.models import Account, LedgerEntry, Voucher
from apps.accounting.services import (
    ApprovalService,
    LedgerService,
    PostingService,
    ReportingService,
    VoucherService,
)
from apps.localization.bs_calendar import ad_to_bs, bs_to_ad
from apps.localization.tax import compute_vat_and_tds, validate_nepal_pan
from apps.projects.models import CostCode, Project
from apps.tenancy.models import Company, FiscalPeriod, FiscalYear


class MayaOSCoreAccountingTests(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.finance = User.objects.create_user(
            username="fin", email="fin@test.local", password="Password@123"
        )
        self.supervisor = User.objects.create_user(
            username="sup", email="sup@test.local", password="Password@123"
        )
        self.company = Company.objects.create(
            code="TESTCO",
            name="Test Construction Ltd",
            pan_vat_no="601234567",
            base_currency="NPR",
            calendar_preference=Company.CalendarPref.BS,
        )
        CompanyMembership.objects.create(
            user=self.finance, company=self.company, role=self.roles["FINANCE_MANAGER"], is_default=True
        )
        CompanyMembership.objects.create(
            user=self.supervisor, company=self.company, role=self.roles["SITE_SUPERVISOR"], is_default=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.grp_exp = Account.objects.create(
            company=self.company,
            code="5000",
            name="Expenses",
            account_type=Account.AccountType.EXPENSE,
            is_group=True,
        )
        self.cash = Account.objects.create(
            company=self.company,
            code="1010",
            name="Cash",
            account_type=Account.AccountType.ASSET,
            opening_debit=Decimal("500000.00"),
        )
        self.equity = Account.objects.create(
            company=self.company,
            code="3010",
            name="Capital",
            account_type=Account.AccountType.EQUITY,
            opening_credit=Decimal("500000.00"),
        )
        self.mat_exp = Account.objects.create(
            company=self.company,
            parent=self.grp_exp,
            code="5010",
            name="Material Expense",
            account_type=Account.AccountType.EXPENSE,
        )
        self.project = Project.objects.create(
            company=self.company,
            code="P-01",
            name="Highway Package",
            budget_amount=Decimal("1000000.00"),
        )
        self.cost_code = CostCode.objects.create(
            company=self.company,
            code="CC-MAT",
            name="Materials",
            category=CostCode.Category.MATERIAL,
        )

    def test_nepal_bs_calendar_and_tax(self):
        ad_d = date(2026, 11, 28)
        bs_d = ad_to_bs(ad_d)
        self.assertEqual(bs_to_ad(bs_d.year, bs_d.month, bs_d.day), ad_d)
        self.assertEqual(bs_d.fiscal_year_label, "2083/84")
        self.assertTrue(validate_nepal_pan("601234567"))
        self.assertFalse(validate_nepal_pan("12345"))

        tax = compute_vat_and_tds(Decimal("100000.00"), Decimal("13.00"), Decimal("1.50"))
        self.assertEqual(tax["vat_amount"], Decimal("13000.00"))
        self.assertEqual(tax["gross_amount"], Decimal("113000.00"))
        self.assertEqual(tax["tds_amount"], Decimal("1500.00"))
        self.assertEqual(tax["net_payable"], Decimal("111500.00"))

    def test_double_entry_posting_immutability_and_reversal(self):
        v_date = date(2026, 11, 28)
        # Unbalanced cannot be submitted
        unbalanced = VoucherService.create_draft(
            company=self.company,
            user=self.finance,
            data={"voucher_type": Voucher.VoucherType.PAYMENT, "voucher_date": v_date},
            lines_data=[
                {"account": self.mat_exp, "debit": Decimal("1000.00"), "credit": Decimal("0.00")},
                {"account": self.cash, "debit": Decimal("0.00"), "credit": Decimal("900.00")},
            ],
        )
        with self.assertRaises(ValidationError):
            VoucherService.submit_voucher(voucher=unbalanced, user=self.finance)

        # Group account cannot be posted
        grp_v = VoucherService.create_draft(
            company=self.company,
            user=self.finance,
            data={"voucher_type": Voucher.VoucherType.PAYMENT, "voucher_date": v_date},
            lines_data=[
                {"account": self.grp_exp, "debit": Decimal("1000.00"), "credit": Decimal("0.00")},
                {"account": self.cash, "debit": Decimal("0.00"), "credit": Decimal("1000.00")},
            ],
        )
        with self.assertRaises(ValidationError):
            VoucherService.submit_voucher(voucher=grp_v, user=self.finance)

        # Balanced workflow: Draft -> Submit -> Approve -> Post (maker-checker separation)
        v = VoucherService.create_draft(
            company=self.company,
            user=self.supervisor,
            data={
                "voucher_type": Voucher.VoucherType.PAYMENT,
                "voucher_date": v_date,
                "project": self.project,
                "narration": "Cement purchase",
            },
            lines_data=[
                {
                    "account": self.mat_exp,
                    "debit": Decimal("25000.00"),
                    "credit": Decimal("0.00"),
                    "project": self.project,
                    "cost_code": self.cost_code,
                },
                {"account": self.cash, "debit": Decimal("0.00"), "credit": Decimal("25000.00")},
            ],
        )
        v = VoucherService.submit_voucher(voucher=v, user=self.supervisor)
        # Creator cannot self-approve
        with self.assertRaises(ValidationError):
            ApprovalService.approve_voucher(voucher=v, user=self.supervisor)
        v = ApprovalService.approve_voucher(voucher=v, user=self.finance, comment="Verified site challan")
        v = PostingService.post_voucher(voucher=v, user=self.finance)

        self.assertTrue(v.voucher_no.startswith("PV-208384-"))
        self.assertEqual(LedgerEntry.objects.filter(voucher=v).count(), 2)

        # Posted voucher & ledger entries are immutable
        v.narration = "Tampered"
        with self.assertRaises(ValidationError):
            v.save()
        le = LedgerEntry.objects.filter(voucher=v).first()
        with self.assertRaises(PermissionError):
            le.delete()

        # Trial Balance & Balance Sheet reconcile
        tb = ReportingService.get_trial_balance(company=self.company)
        self.assertTrue(tb["is_balanced"])
        bs = ReportingService.get_balance_sheet(company=self.company)
        self.assertTrue(bs["is_balanced"])

        # Reversal creates counter-entries and zeroes net effect
        rev = PostingService.reverse_voucher(
            voucher=v, user=self.finance, reversal_date=v_date, reason="Wrong site"
        )
        v.refresh_from_db()
        self.assertEqual(v.status, Voucher.Status.REVERSED)
        self.assertEqual(rev.status, Voucher.Status.POSTED)

        ledger = LedgerService.get_account_ledger(company=self.company, account=self.cash)
        self.assertEqual(Decimal(ledger["closing_balance"]), Decimal("500000.00"))

    def test_locked_period_blocks_posting(self):
        v_date = date(2026, 11, 28)
        period = FiscalPeriod.objects.get(
            fiscal_year=self.fy, start_date__lte=v_date, end_date__gte=v_date
        )
        period.status = FiscalPeriod.Status.LOCKED
        period.save()

        with self.assertRaises(ValidationError):
            VoucherService.create_draft(
                company=self.company,
                user=self.finance,
                data={"voucher_type": Voucher.VoucherType.PAYMENT, "voucher_date": v_date},
                lines_data=[
                    {"account": self.mat_exp, "debit": Decimal("500.00"), "credit": Decimal("0.00")},
                    {"account": self.cash, "debit": Decimal("0.00"), "credit": Decimal("500.00")},
                ],
            )

    def test_rbac_and_offline_sync_idempotency(self):
        client = APIClient()
        client.force_authenticate(user=self.supervisor)
        headers = {"HTTP_X_COMPANY_ID": str(self.company.id), "HTTP_X_DEVICE_ID": "tab-01"}

        # Offline sync push creates server-side DRAFT safely
        push_payload = {
            "operations": [
                {
                    "operation_id": "op-uuid-001",
                    "device_id": "tab-01",
                    "entity_type": "expense_voucher",
                    "entity_id": "local-1",
                    "operation": "create",
                    "payload": {
                        "voucher_type": "PAYMENT",
                        "voucher_date": "2026-11-28",
                        "project": str(self.project.id),
                        "narration": "Offline diesel purchase",
                        "lines": [
                            {"account": str(self.mat_exp.id), "debit": "12000.00", "credit": "0.00"},
                            {"account": str(self.cash.id), "debit": "0.00", "credit": "12000.00"},
                        ],
                    },
                }
            ]
        }
        r1 = client.post("/api/v1/sync/push/", push_payload, format="json", **headers)
        self.assertEqual(r1.status_code, 200)
        self.assertEqual(r1.data["results"][0]["status"], "APPLIED")
        voucher_id = r1.data["results"][0]["voucher_id"]

        # Duplicate operation_id does NOT create duplicate voucher
        r2 = client.post("/api/v1/sync/push/", push_payload, format="json", **headers)
        self.assertEqual(r2.data["results"][0]["status"], "DUPLICATE")
        self.assertEqual(Voucher.objects.filter(company=self.company).count(), 1)

        # Site Supervisor cannot approve or post voucher
        r_app = client.post(f"/api/v1/vouchers/{voucher_id}/approve/", {}, format="json", **headers)
        self.assertEqual(r_app.status_code, 403)
        r_post = client.post(f"/api/v1/vouchers/{voucher_id}/post/", {}, format="json", **headers)
        self.assertEqual(r_post.status_code, 403)

        # Revoked device is blocked
        Device.objects.create(
            user=self.supervisor,
            company=self.company,
            device_id="tab-01",
            device_name="Site Tablet",
            status=Device.Status.REVOKED,
        )
        r_revoked = client.get("/api/v1/accounts/", **headers)
        self.assertEqual(r_revoked.status_code, 403)
