from datetime import date
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, Voucher
from apps.accounting.services import ApprovalService, PostingService, VoucherService
from apps.localization.bs_calendar import bs_to_ad
from apps.projects.models import CostCode, Project, Site
from apps.tenancy.models import Branch, Company, FiscalYear


class EnterpriseDashboardAPITests(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 = User.objects.create_user(
            username="admin_u", email="adm@test.local", full_name="Aarav Shrestha", password="Password@123"
        )
        self.accountant = User.objects.create_user(
            username="acc_u", email="acc@test.local", full_name="Ramesh Karki", password="Password@123"
        )
        self.supervisor = User.objects.create_user(
            username="sup_u", email="sup@test.local", full_name="Bikash Gurung", password="Password@123"
        )

        self.company = Company.objects.create(
            code="DTEST", name="Dashboard Test Construction", 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_user, 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.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.cash = Account.objects.create(
            company=self.company, code="1010", name="Cash", account_type=Account.AccountType.ASSET, opening_debit=Decimal("100000.00")
        )
        self.bank = Account.objects.create(
            company=self.company, code="1020", name="Bank", account_type=Account.AccountType.ASSET, opening_debit=Decimal("500000.00")
        )
        self.ar = Account.objects.create(
            company=self.company, code="1100", name="Receivable", account_type=Account.AccountType.ASSET
        )
        self.ap = Account.objects.create(
            company=self.company, code="2010", name="Payable", account_type=Account.AccountType.LIABILITY
        )
        self.equity = Account.objects.create(
            company=self.company, code="3010", name="Capital", account_type=Account.AccountType.EQUITY, opening_credit=Decimal("600000.00")
        )
        self.rev = Account.objects.create(
            company=self.company, code="4010", name="Contract Revenue", account_type=Account.AccountType.INCOME
        )
        self.exp_mat = Account.objects.create(
            company=self.company, code="5010", name="Material Expense", account_type=Account.AccountType.EXPENSE
        )

        self.project = Project.objects.create(
            company=self.company, code="P-01", name="Bridge Package", contract_amount=Decimal("2000000.00"), budget_amount=Decimal("500000.00")
        )
        Site.objects.create(project=self.project, code="S-01", name="Site Alpha")
        self.cc_mat = CostCode.objects.create(
            company=self.company, code="CC-MAT", name="Materials", category=CostCode.Category.MATERIAL
        )

        # Posted purchase + sales + receipt
        v_sales = VoucherService.create_draft(
            company=self.company,
            user=self.accountant,
            data={"voucher_type": Voucher.VoucherType.SALES, "voucher_date": date(2026, 10, 15), "project": self.project, "party_name": "Client X"},
            lines_data=[
                {"account": self.ar, "debit": Decimal("300000.00"), "credit": Decimal("0.00")},
                {"account": self.rev, "debit": Decimal("0.00"), "credit": Decimal("300000.00"), "project": self.project},
            ],
        )
        VoucherService.submit_voucher(voucher=v_sales, user=self.accountant)
        ApprovalService.approve_voucher(voucher=v_sales, user=self.admin_user)
        PostingService.post_voucher(voucher=v_sales, user=self.admin_user)

        v_pur = VoucherService.create_draft(
            company=self.company,
            user=self.accountant,
            data={"voucher_type": Voucher.VoucherType.PURCHASE, "voucher_date": date(2026, 11, 10), "project": self.project, "party_name": "Supplier Y"},
            lines_data=[
                {"account": self.exp_mat, "debit": Decimal("120000.00"), "credit": Decimal("0.00"), "project": self.project, "cost_code": self.cc_mat},
                {"account": self.ap, "debit": Decimal("0.00"), "credit": Decimal("120000.00")},
            ],
        )
        VoucherService.submit_voucher(voucher=v_pur, user=self.accountant)
        ApprovalService.approve_voucher(voucher=v_pur, user=self.admin_user)
        PostingService.post_voucher(voucher=v_pur, user=self.admin_user)

        # Pending voucher awaiting approval
        v_pend = VoucherService.create_draft(
            company=self.company,
            user=self.accountant,
            data={"voucher_type": Voucher.VoucherType.PAYMENT, "voucher_date": date(2026, 11, 25), "project": self.project, "party_name": "Pending Pay"},
            lines_data=[
                {"account": self.exp_mat, "debit": Decimal("50000.00"), "credit": Decimal("0.00"), "project": self.project, "cost_code": self.cc_mat},
                {"account": self.bank, "debit": Decimal("0.00"), "credit": Decimal("50000.00")},
            ],
        )
        VoucherService.submit_voucher(voucher=v_pend, user=self.accountant)

    def test_dashboard_endpoints_reconciliation_and_preferences(self):
        client = APIClient()
        client.force_authenticate(user=self.admin_user)
        headers = {"HTTP_X_COMPANY_ID": str(self.company.id)}

        r_greet = client.get("/api/v1/dashboard/greeting/", **headers)
        self.assertEqual(r_greet.status_code, 200)
        self.assertEqual(r_greet.data["first_name"], "Aarav")
        self.assertEqual(r_greet.data["timezone"], "Asia/Kathmandu")

        r_sum = client.get("/api/v1/dashboard/summary/", **headers)
        self.assertEqual(r_sum.status_code, 200)
        kpis = r_sum.data["kpis"]
        self.assertEqual(Decimal(kpis["cash"]["value"]), Decimal("100000.00"))
        self.assertEqual(Decimal(kpis["bank"]["value"]), Decimal("500000.00"))
        self.assertEqual(Decimal(kpis["receivable"]["value"]), Decimal("300000.00"))
        self.assertEqual(Decimal(kpis["payable"]["value"]), Decimal("120000.00"))
        self.assertEqual(Decimal(kpis["total_revenue"]["value"]), Decimal("300000.00"))
        self.assertEqual(Decimal(kpis["total_expenses"]["value"]), Decimal("120000.00"))
        self.assertEqual(Decimal(kpis["net_profit"]["value"]), Decimal("180000.00"))
        self.assertEqual(kpis["pending_vouchers"]["value"], "1")

        # Reconciles with Trial Balance and P&L endpoints
        r_tb = client.get("/api/v1/reports/trial-balance/", **headers)
        r_pl = client.get("/api/v1/reports/profit-loss/", **headers)
        self.assertTrue(r_tb.data["is_balanced"])
        self.assertEqual(kpis["net_profit"]["value"], r_pl.data["net_profit"])

        for endpoint in [
            "/api/v1/dashboard/quick-actions/",
            "/api/v1/dashboard/pending-vouchers/",
            "/api/v1/dashboard/recent-transactions/",
            "/api/v1/dashboard/financial-analytics/",
            "/api/v1/dashboard/project-performance/",
            "/api/v1/dashboard/aging/",
            "/api/v1/dashboard/alerts/",
            "/api/v1/dashboard/activity/",
            "/api/v1/dashboard/reports/",
        ]:
            resp = client.get(endpoint, **headers)
            self.assertEqual(resp.status_code, 200, f"Failed on {endpoint}")

        # Preferences GET + PUT + reset
        r_pref = client.get("/api/v1/dashboard/preferences/", **headers)
        self.assertEqual(r_pref.status_code, 200)
        self.assertEqual(r_pref.data["theme"], "light")

        r_put = client.put(
            "/api/v1/dashboard/preferences/",
            {"theme": "dark", "density": "compact", "refresh_interval_sec": 30},
            format="json",
            **headers,
        )
        self.assertEqual(r_put.status_code, 200)
        self.assertEqual(r_put.data["theme"], "dark")
        self.assertEqual(r_put.data["density"], "compact")

        # Site supervisor cannot access audit activity
        sup_client = APIClient()
        sup_client.force_authenticate(user=self.supervisor)
        r_act_denied = sup_client.get("/api/v1/dashboard/activity/", **headers)
        self.assertEqual(r_act_denied.status_code, 403)

