from datetime import date

from django.core.exceptions import PermissionDenied, ValidationError

from apps.approvals.models import ValidationRequest
from apps.approvals.services import decide, open_request
from apps.finance.models import (Budget, BudgetCategory, BudgetLine, Expense,
                                 FinancialEvent, FiscalYear)
from apps.finance.services import (create_expense, record_payment, submit_expense)

from .base import BaseDataTestCase


class FinanceTestCase(BaseDataTestCase):
    def setUp(self):
        self.year, _ = FiscalYear.objects.get_or_create(
            agency=self.agency, year=date.today().year,
            defaults={"start_date": date(date.today().year, 1, 1),
                      "end_date": date(date.today().year, 12, 31), "status": "OPEN"},
        )
        self.budget, _ = Budget.objects.get_or_create(
            agency=self.agency, fiscal_year=self.year, version_number=1,
            defaults={"code": f"DLA-BUD{str(self.year.year)[-2:]}-001", "status": "APPROVED"},
        )
        self.category, _ = BudgetCategory.objects.get_or_create(
            code="CONSO", scope="NATIONAL", agency=None, defaults={"name_fr": "Consommables"})
        self.line, _ = BudgetLine.objects.get_or_create(
            budget=self.budget, category=self.category, activity=None, funding_source=None,
            defaults={"planned_xaf": 1_000_000, "approved_xaf": 1_000_000},
        )

    def _expense(self, amount=45_000, actor=None):
        return create_expense(actor=actor or self.accountant, agency=self.agency, data={
            "fiscal_year": self.year, "budget_line": self.line, "category": self.category,
            "label": "Achat test", "amount_xaf": amount, "incurred_on": date.today(),
        })

    def test_expense_workflow_creates_immutable_event(self):
        expense = self._expense()
        submit_expense(actor=self.accountant, expense=expense)
        expense.refresh_from_db()
        self.assertEqual(expense.status, "PENDING")
        validation = ValidationRequest.objects.get(entity_type="finance.Expense", entity_id=expense.id)
        decide(request_id=validation.id, actor=self.manager, decision="APPROVE", comment="OK")
        expense.refresh_from_db()
        self.assertEqual(expense.status, "APPROVED")
        event = FinancialEvent.objects.get(agency=self.agency, entity_id=expense.id)
        self.assertEqual(event.amount_xaf, 45_000)
        self.assertTrue(event.hash)
        self.assertEqual(event.ledger_seq, 1)

    def test_financial_event_is_immutable(self):
        expense = self._expense()
        submit_expense(actor=self.accountant, expense=expense)
        validation = ValidationRequest.objects.get(entity_type="finance.Expense", entity_id=expense.id)
        decide(request_id=validation.id, actor=self.manager, decision="APPROVE", comment="OK")
        event = FinancialEvent.objects.get(entity_id=expense.id)
        event.amount_xaf = 1
        with self.assertRaises(ValidationError):
            event.save()
        with self.assertRaises(ValidationError):
            event.delete()

    def test_approved_expense_cannot_be_altered(self):
        expense = self._expense()
        submit_expense(actor=self.accountant, expense=expense)
        validation = ValidationRequest.objects.get(entity_type="finance.Expense", entity_id=expense.id)
        decide(request_id=validation.id, actor=self.manager, decision="APPROVE", comment="OK")
        expense.refresh_from_db()
        expense.amount_xaf = 1_000_000
        with self.assertRaises(ValidationError):
            expense.save()

    def test_self_approval_forbidden_above_threshold(self):
        expense = self._expense(amount=300_000, actor=self.manager)
        submit_expense(actor=self.manager, expense=expense)
        validation = ValidationRequest.objects.get(entity_type="finance.Expense", entity_id=expense.id)
        with self.assertRaises(PermissionDenied):
            decide(request_id=validation.id, actor=self.manager, decision="APPROVE", comment="auto")

    def test_payment_requires_justificative(self):
        expense = self._expense()
        submit_expense(actor=self.accountant, expense=expense)
        validation = ValidationRequest.objects.get(entity_type="finance.Expense", entity_id=expense.id)
        decide(request_id=validation.id, actor=self.manager, decision="APPROVE", comment="OK")
        expense.refresh_from_db()
        with self.assertRaises(ValidationError):
            record_payment(actor=self.accountant, expense=expense, amount_xaf=10_000, method="CASH")
        from django.core.files.base import ContentFile
        expense.document.save("justif.txt", ContentFile(b"piece"), save=True)
        payment = record_payment(actor=self.accountant, expense=expense, amount_xaf=10_000, method="CASH")
        expense.refresh_from_db()
        self.assertEqual(expense.status, "PARTIALLY_PAID")
        record_payment(actor=self.accountant, expense=expense, amount_xaf=35_000, method="CASH")
        expense.refresh_from_db()
        self.assertEqual(expense.status, "PAID")
        self.assertEqual(expense.paid_total, 45_000)
        self.assertEqual(payment.amount_xaf, 10_000)

    def test_budget_available_blocks_overspend(self):
        with self.assertRaises(ValidationError):
            self._expense(amount=2_000_000)

    def test_ledger_hash_chain(self):
        first = FinancialEvent(
            agency=self.agency, fiscal_year=self.year, event_type="TEST", entity_type="x.Y",
            entity_id=self.agency.id, amount_xaf=100, ledger_seq=1,
        )
        first.hash = first.compute_hash("")
        first.save()
        second = FinancialEvent(
            agency=self.agency, fiscal_year=self.year, event_type="TEST", entity_type="x.Y",
            entity_id=self.agency.id, amount_xaf=200, ledger_seq=2, prev_hash=first.hash,
        )
        second.hash = second.compute_hash(first.hash)
        second.save()
        self.assertEqual(second.prev_hash, first.hash)
        self.assertNotEqual(second.hash, first.hash)
