from datetime import date, timedelta
from decimal import Decimal

from django.test import TransactionTestCase
from django.utils import timezone
from rest_framework.test import APIClient

from apps.accounting.models import Account, EquipmentAsset, LedgerEntry, Party, Voucher
from apps.accounts_rbac.constants import ROLE_PRESETS
from apps.accounts_rbac.models import CompanyMembership, Role, User
from apps.fleet.models import (
    Vehicle,
    VehicleAssetLink,
    VehicleCostAllocation,
    VehicleExpense,
    VehicleFuelTransaction,
    VehicleIncome,
    VehicleSecurityDeposit,
    VehicleTrip,
)
from apps.fleet.services import VehicleMasterService
from apps.inventory.models import ItemCategory, ItemMaster, StockMovement, UnitOfMeasure, Warehouse
from apps.localization.bs_calendar import bs_to_ad
from apps.notifications.models import Notification
from apps.party_hub.models import OpenItem
from apps.projects.models import Project
from apps.tenancy.models import Company, FiscalYear


class EnterpriseVehicleFleetTests(TransactionTestCase):
    """Comprehensive 22-scenario verification suite for Maya OS Enterprise Vehicle & Fleet Management."""

    def setUp(self):
        self.roles = {
            code: Role.objects.create(
                code=code,
                name=spec["name"],
                description=spec["description"],
                permissions=spec["permissions"],
                is_system=True,
            )
            for code, spec in ROLE_PRESETS.items()
        }
        self.company = Company.objects.create(code="FLT1", name="Maya Construction & Fleet Ltd", base_currency="NPR")
        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.admin = User.objects.create_user(username="flt_admin", email="fadmin@flt.local", password="Password@123", full_name="Fleet Admin")
        self.fm = User.objects.create_user(username="flt_fm", email="ffm@flt.local", password="Password@123", full_name="Finance Manager")
        self.sup = User.objects.create_user(username="flt_sup", email="fsup@flt.local", password="Password@123", full_name="Site Supervisor")

        CompanyMembership.objects.create(user=self.admin, company=self.company, role=self.roles["COMPANY_ADMIN"], is_default=True)
        CompanyMembership.objects.create(user=self.fm, company=self.company, role=self.roles["FINANCE_DIRECTOR"], is_default=True)
        CompanyMembership.objects.create(user=self.sup, company=self.company, role=self.roles["SITE_SUPERVISOR"], is_default=True)

        self.project = Project.objects.create(company=self.company, code="HWY-01", name="Highway Widening")
        self.customer = Party.objects.create(company=self.company, party_type="CUSTOMER", code="CUST-01", name="Summit Infra Ltd")
        self.supplier = Party.objects.create(company=self.company, party_type="SUPPLIER", code="SUP-01", name="Everest Heavy Rentals")

        self.uom_l = UnitOfMeasure.objects.create(company=self.company, code="LTR", name="Liter")
        self.cat_fuel = ItemCategory.objects.create(company=self.company, code="FUEL", name="Petroleum Fuel")
        self.fuel_inv_acc = Account.objects.create(
            company=self.company, code="1180", name="Fuel & Lubricants Inventory", account_type="ASSET", control_role=Account.ControlRole.INVENTORY
        )
        self.warehouse = Warehouse.objects.create(company=self.company, code="WH-YD", name="Central Fuel Yard", store_kind="EQUIPMENT_YARD")
        self.diesel = ItemMaster.objects.create(
            company=self.company, item_code="DSL-01", name="HSD Diesel", category=self.cat_fuel, primary_unit=self.uom_l, inventory_account=self.fuel_inv_acc
        )

    def _client(self, user: User) -> APIClient:
        c = APIClient()
        c.force_authenticate(user=user)
        c.defaults["HTTP_X_COMPANY_ID"] = str(self.company.id)
        return c

    def test_01_vehicle_registration_asset_link_rental_agreements_and_expiry_alerts(self):
        c_admin = self._client(self.admin)

        # Register own vehicle (links automatically to EquipmentAsset without duplicating Fixed Asset ledger)
        own = c_admin.post(
            "/api/vehicles/",
            {
                "ownership_type": "OWNED",
                "registration_number": "BA-2-KHA-1001",
                "name": "Company Tipper 01",
                "vehicle_type": "TIPPER",
                "project_id": str(self.project.id),
                "purchase_price": "4500000.00",
                "current_odometer": "12000",
            },
            format="json",
        )
        self.assertEqual(own.status_code, 201)
        own_id = own.data["id"]
        self.assertTrue(VehicleAssetLink.objects.filter(company=self.company, vehicle_id=own_id).exists())
        self.assertTrue(EquipmentAsset.objects.filter(company=self.company, code=own.data["vehicle_code"]).exists())

        # Register rented-in vehicle
        rnt = c_admin.post(
            "/api/vehicles/",
            {
                "ownership_type": "RENTED_IN",
                "registration_number": "NA-1-GA-9988",
                "name": "Rented Excavator ZX200",
                "vehicle_type": "EXCAVATOR",
                "supplier_id": str(self.supplier.id),
                "project_id": str(self.project.id),
            },
            format="json",
        )
        self.assertEqual(rnt.status_code, 201)
        rnt_id = rnt.data["id"]

        # Insurance document near expiry triggers notification
        c_admin.post(
            f"/api/vehicles/{own_id}/documents/",
            {"doc_type": "INSURANCE", "document_number": "INS-990", "expiry_date": (date.today() + timedelta(days=5)).isoformat(), "reminder_days_before": 15},
            format="json",
        )
        emitted = VehicleMasterService.check_upcoming_renewals(company=self.company)
        self.assertGreaterEqual(emitted, 1)
        self.assertTrue(Notification.objects.filter(company=self.company, event_type="fleet.document_expiring").exists())

        # Rental agreements: Rented-in blocked from HIRED_OUT; Own allowed for HIRED_OUT
        bad_agr = c_admin.post(
            "/api/vehicles/rentals/",
            {"direction": "HIRED_OUT", "vehicle_id": rnt_id, "party_id": str(self.customer.id), "start_date": date.today().isoformat(), "base_rate": "5000"},
            format="json",
        )
        self.assertEqual(bad_agr.status_code, 400)

        good_agr = c_admin.post(
            "/api/vehicles/rentals/",
            {"direction": "HIRED_OUT", "vehicle_id": own_id, "party_id": str(self.customer.id), "start_date": date.today().isoformat(), "base_rate": "8000"},
            format="json",
        )
        self.assertEqual(good_agr.status_code, 201)
        self.assertEqual(c_admin.post(f"/api/vehicles/rentals/{good_agr.data['id']}/approve/").status_code, 200)

    def test_02_single_entry_vs_double_entry_accounting_and_party_settlements(self):
        c_fm = self._client(self.fm)
        own = c_fm.post("/api/vehicles/", {"ownership_type": "OWNED", "registration_number": "BA-1-KHA-1234", "name": "Tipper Cash", "vehicle_type": "TIPPER"}, format="json").data
        rnt = c_fm.post("/api/vehicles/", {"ownership_type": "RENTED_IN", "registration_number": "BA-3-KA-5500", "name": "Rented Tipper", "supplier_id": str(self.supplier.id), "project_id": str(self.project.id)}, format="json").data

        # Single Entry Cash Income: NO customer party, Dr Cash / Cr Vehicle Hire Income (8,000), ZERO OpenItem
        self.assertEqual(
            c_fm.post("/api/vehicles/income/single-entry/", {"vehicle_id": own["id"], "payment_method": "CREDIT", "amount": "8000"}, format="json").status_code,
            400,
        )
        se_inc = c_fm.post(
            "/api/vehicles/income/single-entry/",
            {"vehicle_id": own["id"], "payment_method": "CASH", "amount": "8000.00", "narration": "Direct sand transport cash trip"},
            format="json",
        )
        self.assertEqual(se_inc.status_code, 201)
        inc_obj = VehicleIncome.objects.get(id=se_inc.data["id"])
        self.assertIsNone(inc_obj.party)
        self.assertEqual(inc_obj.voucher.status, Voucher.Status.POSTED)
        self.assertEqual(OpenItem.objects.filter(company=self.company, voucher=inc_obj.voucher).count(), 0)
        # Verify Cash debited & 4150 credited
        self.assertTrue(LedgerEntry.objects.filter(voucher=inc_obj.voucher, account__control_role=Account.ControlRole.CASH, base_debit=Decimal("8000.00")).exists())
        self.assertTrue(LedgerEntry.objects.filter(voucher=inc_obj.voucher, account__code="4150", base_credit=Decimal("8000.00")).exists())

        # Single Entry Cash Expense: NO supplier payable
        se_exp = c_fm.post(
            "/api/vehicles/expenses/single-entry/",
            {"vehicle_id": own["id"], "payment_method": "CASH", "amount": "2000.00", "narration": "Minor brake repair"},
            format="json",
        )
        self.assertEqual(se_exp.status_code, 201)
        exp_obj = VehicleExpense.objects.get(id=se_exp.data["id"])
        self.assertIsNone(exp_obj.party)
        self.assertEqual(OpenItem.objects.filter(company=self.company, voucher=exp_obj.voucher).count(), 0)

        # Double Entry Credit Customer Hire Invoice -> Creates Sundry Debtors OpenItem, Receipt reduces it
        self.assertEqual(
            c_fm.post("/api/vehicles/income/double-entry/", {"vehicle_id": own["id"], "payment_method": "CREDIT", "amount": "50000"}, format="json").status_code,
            400,
        )
        # Rented vehicle blocked from earning customer income
        self.assertEqual(
            c_fm.post("/api/vehicles/income/double-entry/", {"vehicle_id": rnt["id"], "party_id": str(self.customer.id), "payment_method": "CREDIT", "amount": "50000"}, format="json").status_code,
            400,
        )
        de_inc = c_fm.post(
            "/api/vehicles/income/double-entry/",
            {"vehicle_id": own["id"], "party_id": str(self.customer.id), "payment_method": "CREDIT", "amount": "50000.00", "invoice_number": "INV-FLT-01"},
            format="json",
        )
        self.assertEqual(de_inc.status_code, 201)
        cust_bills = c_fm.get("/api/vehicles/income/").data["customer_billings"]
        bill_id = cust_bills[0]["id"]
        rcpt = c_fm.post(
            "/api/vehicles/billings/settle/",
            {"direction": "CUSTOMER_RECEIPT", "billing_id": bill_id, "amount": "50000.00", "payment_method": "BANK"},
            format="json",
        )
        self.assertEqual(rcpt.status_code, 200)
        self.assertEqual(rcpt.data["status"], "SETTLED")

        # Double Entry Rented Vehicle Supplier Expense against Project -> Creates Sundry Creditors OpenItem, Supplier Payment settles it
        de_exp = c_fm.post(
            "/api/vehicles/expenses/double-entry/",
            {"vehicle_id": rnt["id"], "party_id": str(self.supplier.id), "project_id": str(self.project.id), "payment_method": "CREDIT", "amount": "40000.00", "supplier_invoice_no": "SUP-RNT-9"},
            format="json",
        )
        self.assertEqual(de_exp.status_code, 201)
        sup_bills = c_fm.get("/api/vehicles/expenses/").data["supplier_billings"]
        pay = c_fm.post(
            "/api/vehicles/billings/settle/",
            {"direction": "SUPPLIER_PAYMENT", "billing_id": sup_bills[0]["id"], "amount": "40000.00", "payment_method": "BANK"},
            format="json",
        )
        self.assertEqual(pay.status_code, 200)
        self.assertEqual(pay.data["status"], "SETTLED")

    def test_03_trips_overlap_odometer_fuel_stock_internal_allocation_deposits_and_reports(self):
        c_fm = self._client(self.fm)
        c_sup = self._client(self.sup)

        own = c_fm.post("/api/vehicles/", {"ownership_type": "OWNED", "registration_number": "BA-5-CHA-7777", "name": "Loader 07", "current_odometer": "500", "current_engine_hours": "100"}, format="json").data
        drv = c_fm.post("/api/vehicles/drivers/", {"full_name": "Ram Bahadur", "license_number": "LIC-44210"}, format="json").data

        # Negative odometer jump without override blocked
        t0 = timezone.now() - timedelta(hours=4)
        t1 = timezone.now() - timedelta(hours=1)
        bad_odo = c_sup.post(
            "/api/vehicles/trips/",
            {"vehicle_id": own["id"], "start_location": "A", "destination": "B", "start_datetime": t0.isoformat(), "end_datetime": t1.isoformat(), "start_odometer": "500", "end_odometer": "450"},
            format="json",
        )
        self.assertEqual(bad_odo.status_code, 400)

        # Valid trip computes 120 km & 3 engine hours
        tr = c_sup.post(
            "/api/vehicles/trips/",
            {
                "vehicle_id": own["id"],
                "driver_id": drv["id"],
                "start_location": "Depot",
                "destination": "Highway KM 40",
                "start_datetime": t0.isoformat(),
                "end_datetime": t1.isoformat(),
                "start_odometer": "500",
                "end_odometer": "620",
                "start_engine_hours": "100",
                "end_engine_hours": "103",
            },
            format="json",
        )
        self.assertEqual(tr.status_code, 201)
        self.assertEqual(Decimal(tr.data["distance_km"]), Decimal("120.00"))
        self.assertEqual(Decimal(tr.data["operating_hours"]), Decimal("3.00"))

        # Overlapping trip on same vehicle/driver blocked!
        ov = c_sup.post(
            "/api/vehicles/trips/",
            {"vehicle_id": own["id"], "driver_id": drv["id"], "start_location": "X", "destination": "Y", "start_datetime": (t0 + timedelta(minutes=30)).isoformat(), "end_datetime": t1.isoformat()},
            format="json",
        )
        self.assertEqual(ov.status_code, 400)

        # Trip lifecycle Draft -> Submitted -> Verified -> Approved
        tid = tr.data["id"]
        self.assertEqual(c_sup.post(f"/api/vehicles/trips/{tid}/submit/").status_code, 200)
        self.assertEqual(c_sup.post(f"/api/vehicles/trips/{tid}/verify/").status_code, 200)
        self.assertEqual(c_fm.post(f"/api/vehicles/trips/{tid}/approve/").data["status"], "APPROVED")

        # Fuel Stock Purchase -> Stock Issue -> km/L efficiency calculation
        self.assertEqual(
            c_fm.post(
                "/api/vehicles/fuel/",
                {"mode": "STOCK_PURCHASE", "warehouse_id": str(self.warehouse.id), "fuel_item_id": str(self.diesel.id), "quantity": "200", "rate_per_unit": "160", "payment_method": "CASH"},
                format="json",
            ).status_code,
            201,
        )
        # First direct fill @ odometer 1000, second stock issue @ odometer 1200 with 20L -> 10.00 km/L efficiency!
        c_fm.post("/api/vehicles/fuel/", {"mode": "DIRECT_FILL", "vehicle_id": own["id"], "quantity": "20", "rate_per_unit": "160", "odometer_km": "1000"}, format="json")
        f2 = c_fm.post(
            "/api/vehicles/fuel/",
            {"mode": "STOCK_ISSUE", "vehicle_id": own["id"], "warehouse_id": str(self.warehouse.id), "fuel_item_id": str(self.diesel.id), "quantity": "20", "rate_per_unit": "160", "odometer_km": "1200", "project_id": str(self.project.id)},
            format="json",
        )
        self.assertEqual(f2.status_code, 201)
        self.assertEqual(Decimal(f2.data["fuel_efficiency_km_per_unit"]), Decimal("10.00"))
        self.assertEqual(StockMovement.objects.filter(company=self.company, item=self.diesel).count(), 2)

        # Internal Own-Vehicle Cost Allocation creates zero external VehicleIncome!
        alloc = c_fm.post(
            "/api/vehicles/cost-allocations/",
            {"vehicle_id": own["id"], "project_id": str(self.project.id), "basis": "HOURS", "quantity": "5", "rate": "2000"},
            format="json",
        )
        self.assertEqual(alloc.status_code, 201)
        self.assertEqual(VehicleIncome.objects.filter(company=self.company).count(), 0)

        # Security Deposit Paid & Refund stays completely separate from Income & Expense ledgers
        dep = c_fm.post(
            "/api/vehicles/deposits/",
            {"direction": "PAID_TO_OWNER", "vehicle_id": own["id"], "party_id": str(self.supplier.id), "amount": "25000"},
            format="json",
        )
        self.assertEqual(dep.status_code, 201)
        self.assertEqual(VehicleIncome.objects.filter(company=self.company).count(), 0)
        self.assertEqual(c_fm.post(f"/api/vehicles/deposits/{dep.data['id']}/refund/").data["status"], "REFUNDED")

        # Dashboard, Operational Ledger, Profitability & PDF/XLSX/CSV Exports agree cleanly
        dash = c_fm.get("/api/vehicles/dashboard/").data
        self.assertEqual(dash["kpis"]["total_owned"], 1)
        prof = c_fm.get("/api/vehicles/reports/profitability/").data
        self.assertEqual(Decimal(prof[0]["internal_allocated"]), Decimal("10000.00"))

        pdf_res = c_fm.get("/api/vehicles/reports/export/?file_format=pdf")
        self.assertEqual(pdf_res.status_code, 200)
        self.assertTrue(pdf_res.content.startswith(b"%PDF"))
        self.assertEqual(c_fm.get("/api/vehicles/reports/export/?file_format=xlsx").status_code, 200)
        self.assertEqual(c_fm.get("/api/vehicles/reports/export/?file_format=csv").status_code, 200)


    def test_04_enterprise_fleet_capabilities_all_acceptance_criteria(self):
        from apps.fleet.models import RentalSettlement, TripCostCalculation, VehicleAssetLink, VehicleDriverSettlement, VehicleStatusHistory

        c_admin = self._client(self.admin)
        c_fm = self._client(self.fm)
        c_sup = self._client(self.sup)

        # 1. Customer-supplied & Leased vehicles never create company EquipmentAsset links
        cs = c_fm.post(
            "/api/fleet/",
            {
                "ownership_type": "CUSTOMER_SUPPLIED",
                "registration_number": "BA-9-PA-8888",
                "name": "Client Loader",
                "vehicle_type": "LOADER",
                "is_machinery": True,
                "service_km_interval": "2500",
                "normal_fuel_consumption": "4.0",
            },
            format="json",
        )
        self.assertEqual(cs.status_code, 201)
        self.assertEqual(VehicleAssetLink.objects.filter(vehicle_id=cs.data["id"]).count(), 0)

        # 2. Owned vehicle + Driver + Hire-Out Agreement with quantity control
        own = c_fm.post(
            "/api/fleet/",
            {
                "ownership_type": "OWNED",
                "registration_number": "BA-2-KHA-9001",
                "name": "Enterprise Tipper 9001",
                "vehicle_type": "TIPPER",
                "normal_fuel_consumption": "5.00",
                "purchase_price": "4500000",
            },
            format="json",
        )
        self.assertEqual(own.status_code, 201)
        vid = own.data["id"]

        drv = c_fm.post(
            "/api/fleet/drivers/",
            {"full_name": "Bikram Tamang", "license_number": "DL-9901", "contact_number": "9800000001"},
            format="json",
        )
        self.assertEqual(drv.status_code, 201)

        agr = c_fm.post(
            "/api/fleet/rentals/",
            {
                "agreement_number": "HO-2026-001",
                "direction": "HIRED_OUT",
                "vehicle_id": vid,
                "party_id": str(self.customer.id),
                "start_date": "2026-12-01",
                "rate_type": "PER_KM",
                "base_rate": "100.00",
                "contracted_quantity": "200.00",
                "approved_quantity": "200.00",
            },
            format="json",
        )
        self.assertEqual(agr.status_code, 201)
        agr_id = agr.data["id"]
        self.assertEqual(c_fm.post(f"/api/fleet/rentals/{agr_id}/approve/").status_code, 200)

        # 3. Full trip dispatch lifecycle -> APPROVED creates TripCostCalculation
        t0 = timezone.now() - timedelta(hours=3)
        t1 = timezone.now() - timedelta(hours=1)
        tr = c_sup.post(
            "/api/fleet/trips/",
            {
                "vehicle_id": vid,
                "driver_id": drv.data["id"],
                "rental_agreement_id": agr_id,
                "start_location": "Quarry",
                "destination": "Dam Site",
                "trip_type": "MATERIAL_TRANSPORT",
                "load_quantity": "15",
                "load_unit": "MT",
                "start_datetime": t0.isoformat(),
                "end_datetime": t1.isoformat(),
                "start_odometer": "100",
                "end_odometer": "150",
            },
            format="json",
        )
        self.assertEqual(tr.status_code, 201)
        tid = tr.data["id"]
        self.assertEqual(c_sup.post(f"/api/fleet/trips/{tid}/dispatch/").data["status"], "DISPATCHED")
        self.assertEqual(c_sup.post(f"/api/fleet/trips/{tid}/start/").data["status"], "IN_PROGRESS")
        self.assertEqual(c_sup.post(f"/api/fleet/trips/{tid}/complete/").data["status"], "COMPLETED")
        self.assertEqual(c_sup.post(f"/api/fleet/trips/{tid}/verify/").data["status"], "VERIFIED")
        self.assertEqual(c_fm.post(f"/api/fleet/trips/{tid}/approve/").data["status"], "APPROVED")
        self.assertTrue(TripCostCalculation.objects.filter(trip_id=tid, billable_units=Decimal("50.00")).exists())

        # 4. Period Hire-Out Settlement bills APPROVED trips once & blocks duplicate settlement
        settle = c_fm.post(
            f"/api/fleet/rentals/{agr_id}/settle/",
            {"period_start": str((t0 - timedelta(days=1)).date()), "period_end": str((t1 + timedelta(days=1)).date()), "trip_ids": [tid]},
            format="json",
        )
        self.assertEqual(settle.status_code, 201)
        self.assertEqual(Decimal(settle.data["net_amount"]), Decimal("5000.00"))
        self.assertEqual(RentalSettlement.objects.filter(company=self.company).count(), 1)
        # Re-settling the same trip_id is strictly blocked!
        dup_settle = c_fm.post(
            f"/api/fleet/rentals/{agr_id}/settle/",
            {"period_start": str(t0.date()), "period_end": str(t1.date()), "trip_ids": [tid]},
            format="json",
        )
        self.assertEqual(dup_settle.status_code, 400)

        # 5. Single Entry Transaction + Reversal Permission check (Supervisor blocked, Fleet Mgr succeeds)
        se = c_fm.post(
            "/api/fleet/income/single-entry/",
            {"vehicle_id": vid, "payment_method": "CASH", "amount": "2500", "narration": "Spot tipper haul"},
            format="json",
        )
        self.assertEqual(se.status_code, 201)
        inc_id = se.data["id"]
        self.assertEqual(
            c_sup.post("/api/fleet/transactions/reverse/", {"kind": "INCOME", "record_id": inc_id, "reason": "No perm"}, format="json").status_code,
            403,
        )
        rev = c_fm.post("/api/fleet/transactions/reverse/", {"kind": "INCOME", "record_id": inc_id, "reason": "Entered wrong vehicle"}, format="json")
        self.assertEqual(rev.status_code, 200)
        self.assertTrue(rev.data["is_reversed"])

        # 6. Driver Advance issuance & Balanced Driver Expense Settlement
        adv = c_fm.post(
            "/api/fleet/advances/",
            {"kind": "DRIVER_ADVANCE", "driver_id": drv.data["id"], "vehicle_id": vid, "amount": "6000", "notes": "Highway allowance"},
            format="json",
        )
        self.assertEqual(adv.status_code, 201)
        dset = c_fm.post(
            f"/api/fleet/advances/{adv.data['id']}/settle/",
            {"fuel_expense": "2000", "road_toll_expense": "1500", "cash_returned": "2500"},
            format="json",
        )
        self.assertEqual(dset.status_code, 201)
        self.assertEqual(VehicleDriverSettlement.objects.filter(company=self.company).count(), 1)

        # 7. Vehicle Detail Bundle (14 tabs), Status Change, Assignment Board & Config Studio
        st_res = c_fm.post(f"/api/fleet/{vid}/change-status/", {"status": "UNAVAILABLE", "reason": "Waiting crane lift"}, format="json")
        self.assertEqual(st_res.status_code, 200)
        self.assertTrue(VehicleStatusHistory.objects.filter(vehicle_id=vid, new_status="UNAVAILABLE").exists())
        bundle = c_fm.get(f"/api/fleet/{vid}/detail-bundle/").data
        self.assertEqual(bundle["vehicle"]["id"], vid)
        self.assertGreaterEqual(len(bundle["status_history"]), 1)

        board = c_fm.get("/api/fleet/assignment-board/").data
        self.assertGreaterEqual(len(board["vehicles"]), 2)
        self.assertGreaterEqual(len(board["drivers"]), 1)

        cfg = c_admin.put("/api/fleet/config/", {"fuel_accounting_method": "DIRECT_EXPENSE", "allow_odometer_rollover_override": False}, format="json")
        self.assertEqual(cfg.status_code, 200)
        self.assertFalse(cfg.data["allow_odometer_rollover_override"])

        # 8. Maintenance Work Order IN_PROGRESS -> Complete + Schedule
        wo = c_fm.post(
            "/api/fleet/maintenance/",
            {"vehicle_id": vid, "service_type": "BREAKDOWN", "status": "IN_PROGRESS", "work_description": "Brake overhaul", "total_amount": "4500"},
            format="json",
        )
        self.assertEqual(wo.status_code, 201)
        comp = c_fm.post(f"/api/fleet/maintenance/{wo.data['id']}/complete/", {"downtime_hours": "6"}, format="json")
        self.assertEqual(comp.status_code, 200)
        self.assertEqual(comp.data["status"], "COMPLETED")
        self.assertEqual(
            c_fm.post("/api/fleet/maintenance-schedules/", {"vehicle_id": vid, "service_title": "Oil Check", "next_due_km": "2000"}, format="json").status_code,
            201,
        )

        # 9. Offline Sync batch & 50-Report Catalog + A4/A3 PDF Export
        sync = c_sup.post(
            "/api/fleet/sync/push/",
            {"device_id": "tab-01", "operations": [{"client_uuid": "off-001", "operation_type": "SINGLE_ENTRY_EXPENSE", "payload": {"vehicle_id": vid, "payment_method": "CASH", "amount": "450"}}]},
            format="json",
        )
        self.assertEqual(sync.status_code, 200)
        self.assertEqual(sync.data["results"][0]["status"], "SYNCED")

        cat = c_fm.get("/api/fleet/reports/catalog/").data
        self.assertEqual(len(cat["catalog"]), 50)
        for code in ("A1_VEHICLE_MASTER", "B1_TRIP_SUMMARY", "C1_INCOME_REGISTER", "D1_FUEL_LOG", "E1_FLEET_AUDIT_TRAIL"):
            r = c_fm.get(f"/api/fleet/reports/catalog/{code}/")
            self.assertEqual(r.status_code, 200)
        pdf = c_fm.get("/api/fleet/reports/catalog/C5_VEHICLE_PROFITABILITY/?file_format=pdf&page_size=A3&orientation=landscape")
        self.assertEqual(pdf.status_code, 200)
        self.assertTrue(pdf.content.startswith(b"%PDF"))
