from datetime import date, timedelta

from django.contrib.auth import get_user_model
from django.test import TestCase
from rest_framework.test import APIClient

from shop_management.models.data.customer import Customer
from shop_management.models.data.customer_payment import CustomerPayment, CustomerPaymentAllocation
from shop_management.models.data.sale import Sale
from shop_management.models.data.shop import Shop
from shop_management.models.data.shop_account import Account
from shop_management.models.data.utils import Currency


class AgingReportTests(TestCase):
    def setUp(self):
        self.user = get_user_model().objects.create_superuser(username="aging-admin", password="test")
        self.shop = Shop.objects.create(owner=self.user, name="Kabul")
        self.currency = Currency.objects.create(shop=self.shop, title="AFN")
        self.customer = Customer.objects.create(shop=self.shop, name="Nasim Ltd")
        self.account = Account.objects.create(shop=self.shop, name="Cash", currency=self.currency)
        self.as_of = date(2026, 9, 3)
        self.sale = Sale.objects.create(
            shop=self.shop, customer=self.customer, currency=self.currency,
            invoice_date=self.as_of - timedelta(days=45), due_date=self.as_of - timedelta(days=35),
            calculated_total=1000, uses_inventory_engine=True, document_status=Sale.DocumentStatus.POSTED,
            sale_number="KAB-SAL-2026-000001",
        )
        payment = CustomerPayment.objects.create(customer=self.customer, shop=self.shop, financial_account=self.account, currency=self.currency, amount=250, base_amount=250, status=CustomerPayment.Status.POSTED, payment_date=self.as_of)
        CustomerPaymentAllocation.objects.create(payment=payment, sale=self.sale, allocated_amount=250)
        self.client = APIClient(); self.client.force_authenticate(self.user)

    def test_receivable_aging_uses_due_date_and_allocations(self):
        response = self.client.get("/api/shop/aging-report/", {"type": "receivable", "shop": self.shop.pk, "as_of": self.as_of})
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.data["rows"][0]["bucket"], "31-60")
        self.assertEqual(response.data["rows"][0]["outstanding"], "750.00")
        self.assertEqual(response.data["summary"][0]["31-60"], "750.00")
