import uuid
from decimal import Decimal
from django.conf import settings
from django.core.serializers.json import DjangoJSONEncoder
from django.db import models
from django.utils import timezone


class Vehicle(models.Model):
    class OwnershipType(models.TextChoices):
        OWNED = "OWNED", "Company-Owned Vehicle"
        RENTED_IN = "RENTED_IN", "Rented / Hired-In Vehicle"
        LEASED = "LEASED", "Leased Vehicle"
        CUSTOMER_SUPPLIED = "CUSTOMER_SUPPLIED", "Customer-Supplied Vehicle"
        PROJECT_PROVIDED = "PROJECT_PROVIDED", "Project-Provided Vehicle"
        OTHER = "OTHER", "Other Configurable Ownership"

    class VehicleType(models.TextChoices):
        PICKUP = "PICKUP", "Pickup"
        JEEP = "JEEP", "Jeep"
        CAR = "CAR", "Car"
        VAN = "VAN", "Van"
        BUS = "BUS", "Bus"
        TRUCK = "TRUCK", "Truck"
        TIPPER = "TIPPER", "Tipper / Dumper"
        TRACTOR = "TRACTOR", "Tractor"
        TRAILER = "TRAILER", "Trailer"
        WATER_TANKER = "WATER_TANKER", "Water Tanker"
        EXCAVATOR = "EXCAVATOR", "Excavator"
        BACKHOE_LOADER = "BACKHOE_LOADER", "Backhoe Loader"
        LOADER = "LOADER", "Wheel Loader"
        BULLDOZER = "BULLDOZER", "Bulldozer"
        GRADER = "GRADER", "Motor Grader"
        ROLLER = "ROLLER", "Compactor / Roller"
        CRANE = "CRANE", "Crane"
        CONCRETE_MIXER = "CONCRETE_MIXER", "Concrete Mixer"
        CONCRETE_PUMP = "CONCRETE_PUMP", "Concrete Pump"
        GENERATOR = "GENERATOR", "Diesel Generator"
        MOTORBIKE = "MOTORBIKE", "Motorbike"
        OTHER = "OTHER", "Other Heavy Equipment / Transport"

    class FuelType(models.TextChoices):
        DIESEL = "DIESEL", "Diesel"
        PETROL = "PETROL", "Petrol"
        ELECTRIC = "ELECTRIC", "Electric"
        HYBRID = "HYBRID", "Hybrid"
        CNG = "CNG", "CNG"

    class MeterType(models.TextChoices):
        ODOMETER_KM = "ODOMETER_KM", "Odometer (KM)"
        ENGINE_HOURS = "ENGINE_HOURS", "Engine Hours"
        BOTH = "BOTH", "Both KM & Engine Hours"

    class Status(models.TextChoices):
        AVAILABLE = "AVAILABLE", "Available"
        ASSIGNED = "ASSIGNED", "Assigned"
        TRIP_STARTED = "TRIP_STARTED", "Trip Started"
        ON_TRIP = "ON_TRIP", "On Trip"
        TRIP_COMPLETED = "TRIP_COMPLETED", "Trip Completed"
        HIRED_OUT = "HIRED_OUT", "Hired Out"
        RENTED_IN = "RENTED_IN", "Rented In"
        UNDER_MAINTENANCE = "UNDER_MAINTENANCE", "Under Maintenance"
        UNAVAILABLE = "UNAVAILABLE", "Temporarily Unavailable"
        DAMAGED = "DAMAGED", "Accident / Damaged"
        RETIRED = "RETIRED", "Retired"
        DISPOSED = "DISPOSED", "Disposed"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="vehicles")
    branch = models.ForeignKey("tenancy.Branch", on_delete=models.PROTECT, null=True, blank=True, related_name="vehicles")
    ownership_type = models.CharField(max_length=24, choices=OwnershipType.choices, default=OwnershipType.OWNED, db_index=True)
    vehicle_code = models.CharField(max_length=32)
    registration_number = models.CharField(max_length=48)
    name = models.CharField(max_length=160)
    vehicle_category = models.CharField(max_length=64, default="Transport & Heavy Machinery")
    vehicle_type = models.CharField(max_length=24, choices=VehicleType.choices, default=VehicleType.TIPPER)
    make = models.CharField(max_length=80, blank=True)
    model_name = models.CharField(max_length=80, blank=True)
    manufacturing_year = models.PositiveSmallIntegerField(null=True, blank=True)
    chassis_number = models.CharField(max_length=80, blank=True)
    engine_number = models.CharField(max_length=80, blank=True)
    color = models.CharField(max_length=40, blank=True)
    fuel_type = models.CharField(max_length=16, choices=FuelType.choices, default=FuelType.DIESEL)
    seating_capacity = models.PositiveSmallIntegerField(null=True, blank=True)
    load_capacity = models.CharField(max_length=64, blank=True)
    equipment_capacity = models.CharField(max_length=64, blank=True)
    image_ref = models.CharField(max_length=255, blank=True)

    # Operating & Default Project/Accounting Context
    supplier = models.ForeignKey("accounting.Party", on_delete=models.PROTECT, null=True, blank=True, related_name="rented_vehicles")
    assigned_department = models.ForeignKey("accounting.Department", on_delete=models.SET_NULL, null=True, blank=True)
    assigned_project = models.ForeignKey("projects.Project", on_delete=models.SET_NULL, null=True, blank=True, related_name="vehicles")
    assigned_site = models.ForeignKey("projects.Site", on_delete=models.SET_NULL, null=True, blank=True, related_name="vehicles")
    assigned_cost_center = models.ForeignKey("accounting.CostCenter", on_delete=models.SET_NULL, null=True, blank=True)
    default_driver = models.ForeignKey("fleet.VehicleDriver", on_delete=models.SET_NULL, null=True, blank=True, related_name="default_for_vehicles")
    fuel_responsibility = models.CharField(max_length=24, default="COMPANY")  # COMPANY|OWNER|CUSTOMER|SHARED
    meter_type = models.CharField(max_length=16, choices=MeterType.choices, default=MeterType.ODOMETER_KM)
    current_odometer = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    current_engine_hours = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    normal_fuel_consumption = models.DecimalField(max_digits=8, decimal_places=2, default=Decimal("0.00"))
    service_km_interval = models.DecimalField(max_digits=12, decimal_places=2, default=Decimal("5000.00"))
    engine_hours_interval = models.DecimalField(max_digits=12, decimal_places=2, default=Decimal("250.00"))
    max_load_tonnes = models.DecimalField(max_digits=10, decimal_places=2, default=Decimal("0.00"))
    insurance_provider = models.CharField(max_length=160, blank=True)
    finance_loan_ref = models.CharField(max_length=80, blank=True)
    is_machinery = models.BooleanField(default=False)
    internal_hourly_rate = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    internal_km_rate = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    status = models.CharField(max_length=24, choices=Status.choices, default=Status.AVAILABLE, db_index=True)
    is_available_for_hire_out = models.BooleanField(default=True)
    is_active = models.BooleanField(default=True)
    version = models.PositiveIntegerField(default=1)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "fleet_vehicles"
        unique_together = [("company", "vehicle_code"), ("company", "registration_number")]
        ordering = ["vehicle_code"]

    def __str__(self) -> str:
        return f"{self.registration_number} ({self.name})"


class VehicleOwnership(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    vehicle = models.OneToOneField(Vehicle, on_delete=models.CASCADE, related_name="ownership")
    purchase_date = models.DateField(null=True, blank=True)
    purchase_price = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    seller_party = models.ForeignKey("accounting.Party", on_delete=models.SET_NULL, null=True, blank=True)
    purchase_voucher = models.ForeignKey("accounting.Voucher", on_delete=models.SET_NULL, null=True, blank=True)
    asset_gl_account = models.ForeignKey("accounting.Account", on_delete=models.PROTECT, null=True, blank=True, related_name="fleet_asset_links")
    accum_dep_account = models.ForeignKey("accounting.Account", on_delete=models.PROTECT, null=True, blank=True, related_name="fleet_accum_dep_links")
    loan_facility = models.ForeignKey("loans.BankFacility", on_delete=models.SET_NULL, null=True, blank=True)
    ownership_certificate_no = models.CharField(max_length=80, blank=True)
    notes = models.TextField(blank=True)

    class Meta:
        db_table = "fleet_vehicle_ownerships"


class VehicleAssetLink(models.Model):
    """Links owned fleet vehicle to central Fixed Asset / EquipmentAsset without duplicating asset ledgers."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    vehicle = models.OneToOneField(Vehicle, on_delete=models.CASCADE, related_name="asset_link")
    equipment_asset = models.OneToOneField("accounting.EquipmentAsset", on_delete=models.PROTECT, related_name="fleet_vehicle_link")
    linked_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "fleet_vehicle_asset_links"


class VehicleDocument(models.Model):
    class DocType(models.TextChoices):
        REGISTRATION = "REGISTRATION", "Registration Certificate"
        BLUEBOOK = "BLUEBOOK", "Bluebook"
        INSURANCE = "INSURANCE", "Insurance Policy"
        TAX_PAYMENT = "TAX_PAYMENT", "Vehicle Tax Payment"
        ROUTE_PERMIT = "ROUTE_PERMIT", "Route Permit"
        FITNESS = "FITNESS", "Fitness Certificate"
        POLLUTION = "POLLUTION", "Pollution / Emission Check"
        OWNERSHIP = "OWNERSHIP", "Ownership Deed"
        RENTAL_AGREEMENT = "RENTAL_AGREEMENT", "Signed Rental Agreement"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE, related_name="documents")
    doc_type = models.CharField(max_length=24, choices=DocType.choices, db_index=True)
    document_number = models.CharField(max_length=80, blank=True)
    issue_date = models.DateField(null=True, blank=True)
    expiry_date = models.DateField(null=True, blank=True, db_index=True)
    reminder_days_before = models.PositiveSmallIntegerField(default=15)
    file_ref = models.CharField(max_length=255, blank=True)
    notes = models.TextField(blank=True)
    expiry_alert_sent = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "fleet_vehicle_documents"
        ordering = ["expiry_date", "-created_at"]


class VehicleDriver(models.Model):
    class EngagementType(models.TextChoices):
        EMPLOYEE = "EMPLOYEE", "Company Employee"
        DAILY_CONTRACT = "DAILY_CONTRACT", "Daily Contract Operator"
        TRIP_COMMISSION = "TRIP_COMMISSION", "Per-Trip Operator"
        EXTERNAL_PARTY = "EXTERNAL_PARTY", "External Supplier / Contractor Driver"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="fleet_drivers")
    driver_code = models.CharField(max_length=32)
    employee = models.ForeignKey("hr.EmployeeDetail", on_delete=models.SET_NULL, null=True, blank=True, related_name="fleet_driver_profiles")
    external_party = models.ForeignKey("accounting.Party", on_delete=models.SET_NULL, null=True, blank=True, related_name="external_drivers")
    full_name = models.CharField(max_length=160)
    contact_number = models.CharField(max_length=40, blank=True)
    address = models.TextField(blank=True)
    license_number = models.CharField(max_length=64)
    license_category = models.CharField(max_length=32, blank=True)
    license_expiry_date = models.DateField(null=True, blank=True, db_index=True)
    engagement_type = models.CharField(max_length=24, choices=EngagementType.choices, default=EngagementType.EMPLOYEE)
    salary_or_trip_rate = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    assigned_project = models.ForeignKey("projects.Project", on_delete=models.SET_NULL, null=True, blank=True)
    status = models.CharField(max_length=24, default="ACTIVE")  # ACTIVE|ON_LEAVE|SUSPENDED|INACTIVE
    accident_notes = models.TextField(blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "fleet_drivers"
        unique_together = [("company", "driver_code")]
        ordering = ["driver_code"]

    def __str__(self) -> str:
        return f"{self.driver_code} — {self.full_name}"


class VehicleAssignment(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE, related_name="assignments")
    branch = models.ForeignKey("tenancy.Branch", on_delete=models.SET_NULL, null=True, blank=True)
    department = models.ForeignKey("accounting.Department", on_delete=models.SET_NULL, null=True, blank=True)
    project = models.ForeignKey("projects.Project", on_delete=models.SET_NULL, null=True, blank=True)
    site = models.ForeignKey("projects.Site", on_delete=models.SET_NULL, null=True, blank=True)
    cost_center = models.ForeignKey("accounting.CostCenter", on_delete=models.SET_NULL, null=True, blank=True)
    start_date = models.DateField()
    end_date = models.DateField(null=True, blank=True)
    is_active = models.BooleanField(default=True)
    assigned_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True)

    class Meta:
        db_table = "fleet_vehicle_assignments"
        ordering = ["-start_date"]


class VehicleDriverAssignment(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE, related_name="driver_assignments")
    driver = models.ForeignKey(VehicleDriver, on_delete=models.CASCADE, related_name="vehicle_assignments")
    start_date = models.DateField()
    end_date = models.DateField(null=True, blank=True)
    is_active = models.BooleanField(default=True)
    notes = models.CharField(max_length=255, blank=True)

    class Meta:
        db_table = "fleet_driver_assignments"
        ordering = ["-start_date"]


class VehicleRentalAgreement(models.Model):
    class AgreementDirection(models.TextChoices):
        RENTED_IN = "RENTED_IN", "Rented In (External Supplier -> Company)"
        HIRED_OUT = "HIRED_OUT", "Owned Hired Out (Company -> External Customer)"

    class RateType(models.TextChoices):
        HOURLY = "HOURLY", "Per Operating Hour"
        DAILY = "DAILY", "Per Day"
        MONTHLY = "MONTHLY", "Per Month"
        PER_KM = "PER_KM", "Per Kilometre"
        PER_TRIP = "PER_TRIP", "Per Trip"
        PER_LOAD = "PER_LOAD", "Per Load"
        PER_TONNE = "PER_TONNE", "Per Tonne"
        PER_ENGINE_HOUR = "PER_ENGINE_HOUR", "Per Engine Hour"
        PER_UNIT = "PER_UNIT", "Per Unit of Work"
        FIXED = "FIXED", "Fixed Contract"
        MIXED = "MIXED", "Mixed Rate Agreement"

    class Status(models.TextChoices):
        DRAFT = "DRAFT", "Draft"
        REQUESTED = "REQUESTED", "Requested"
        QUOTATION = "QUOTATION", "Quotation"
        SUBMITTED = "SUBMITTED", "Submitted for Approval"
        APPROVED = "APPROVED", "Approved"
        ACTIVE = "ACTIVE", "Active"
        EXTENDED = "EXTENDED", "Extended"
        IN_PROGRESS = "IN_PROGRESS", "Work in Progress"
        BILLED = "BILLED", "Bill Received / Invoiced"
        COMPLETED = "COMPLETED", "Completed"
        CLOSED = "CLOSED", "Closed"
        TERMINATED = "TERMINATED", "Early Terminated"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="vehicle_rentals")
    branch = models.ForeignKey("tenancy.Branch", on_delete=models.PROTECT, null=True, blank=True)
    agreement_number = models.CharField(max_length=48)
    direction = models.CharField(max_length=16, choices=AgreementDirection.choices, db_index=True)
    vehicle = models.ForeignKey(Vehicle, on_delete=models.PROTECT, related_name="rental_agreements")
    party = models.ForeignKey("accounting.Party", on_delete=models.PROTECT, related_name="vehicle_rentals")
    project = models.ForeignKey("projects.Project", on_delete=models.SET_NULL, null=True, blank=True)
    site = models.ForeignKey("projects.Site", on_delete=models.SET_NULL, null=True, blank=True)
    start_date = models.DateField()
    end_date = models.DateField(null=True, blank=True)
    rate_type = models.CharField(max_length=16, choices=RateType.choices, default=RateType.DAILY)
    base_rate = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    minimum_hire_quantity = models.DecimalField(max_digits=12, decimal_places=2, default=Decimal("0.00"))
    overtime_rate = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    waiting_rate = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    mobilization_charges = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    demobilization_charges = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    security_deposit_amount = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    advance_amount = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    fuel_responsibility = models.CharField(max_length=24, default="COMPANY")
    maintenance_responsibility = models.CharField(max_length=24, default="OWNER")
    operator_responsibility = models.CharField(max_length=24, default="OWNER")
    contract_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    contracted_quantity = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    approved_quantity = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    used_quantity = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    is_terminated_early = models.BooleanField(default=False)
    termination_date = models.DateField(null=True, blank=True)
    termination_reason = models.CharField(max_length=255, blank=True)
    status = models.CharField(max_length=16, choices=Status.choices, default=Status.DRAFT, db_index=True)
    terms_notes = models.TextField(blank=True)
    version = models.PositiveIntegerField(default=1)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="created_rentals")
    approved_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="approved_rentals")
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "fleet_rental_agreements"
        unique_together = [("company", "agreement_number")]
        ordering = ["-start_date", "-created_at"]


class VehicleRentalAgreementRevision(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    agreement = models.ForeignKey(VehicleRentalAgreement, on_delete=models.CASCADE, related_name="revisions")
    revision_no = models.PositiveSmallIntegerField()
    snapshot = models.JSONField(default=dict, encoder=DjangoJSONEncoder)
    reason = models.CharField(max_length=255)
    revised_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "fleet_rental_revisions"
        unique_together = [("agreement", "revision_no")]
        ordering = ["-revision_no"]


class VehicleTrip(models.Model):
    class TripType(models.TextChoices):
        MATERIAL_TRANSPORT = "MATERIAL_TRANSPORT", "Material Transport"
        SITE_MOVEMENT = "SITE_MOVEMENT", "Site-to-Site Movement"
        CUSTOMER_DELIVERY = "CUSTOMER_DELIVERY", "Customer Delivery"
        VEHICLE_HIRE = "VEHICLE_HIRE", "Vehicle Hire Trip"
        STAFF_TRANSPORT = "STAFF_TRANSPORT", "Staff Transportation"
        EQUIPMENT_TRANSPORT = "EQUIPMENT_TRANSPORT", "Equipment Transportation"
        EXCAVATION = "EXCAVATION", "Excavation / Operating Work"
        OTHER = "OTHER", "Other Operations"

    class Status(models.TextChoices):
        DRAFT = "DRAFT", "Draft"
        REQUESTED = "REQUESTED", "Requested"
        ASSIGNED = "ASSIGNED", "Assigned"
        DISPATCHED = "DISPATCHED", "Dispatched"
        IN_PROGRESS = "IN_PROGRESS", "In Progress"
        COMPLETED = "COMPLETED", "Completed"
        SUBMITTED = "SUBMITTED", "Driver Submitted"
        VERIFIED = "VERIFIED", "Site Supervisor Verified"
        APPROVED = "APPROVED", "Project Manager Approved"
        POSTED = "POSTED", "Billed / Posted"
        REJECTED = "REJECTED", "Rejected"
        CANCELLED = "CANCELLED", "Cancelled"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="vehicle_trips")
    branch = models.ForeignKey("tenancy.Branch", on_delete=models.SET_NULL, null=True, blank=True)
    fiscal_year = models.ForeignKey("tenancy.FiscalYear", on_delete=models.PROTECT, null=True, blank=True)
    trip_number = models.CharField(max_length=48)
    vehicle = models.ForeignKey(Vehicle, on_delete=models.PROTECT, related_name="trips")
    ownership_type = models.CharField(max_length=24, choices=Vehicle.OwnershipType.choices)
    driver = models.ForeignKey(VehicleDriver, on_delete=models.PROTECT, null=True, blank=True, related_name="trips")
    rental_agreement = models.ForeignKey(VehicleRentalAgreement, on_delete=models.SET_NULL, null=True, blank=True, related_name="trips")
    project = models.ForeignKey("projects.Project", on_delete=models.SET_NULL, null=True, blank=True, related_name="vehicle_trips")
    site = models.ForeignKey("projects.Site", on_delete=models.SET_NULL, null=True, blank=True)
    start_location = models.CharField(max_length=160)
    destination = models.CharField(max_length=160)
    trip_type = models.CharField(max_length=24, choices=TripType.choices, default=TripType.VEHICLE_HIRE)
    trip_purpose = models.CharField(max_length=160)
    material_passenger_details = models.CharField(max_length=255, blank=True)
    load_quantity = models.DecimalField(max_digits=14, decimal_places=3, default=Decimal("0.000"))
    load_unit = models.CharField(max_length=24, blank=True)
    rate_source = models.CharField(max_length=16, default="AGREEMENT")  # AGREEMENT|MANUAL|INTERNAL
    is_billed = models.BooleanField(default=False)
    rejection_reason = models.CharField(max_length=255, blank=True)
    start_datetime = models.DateTimeField(db_index=True)
    end_datetime = models.DateTimeField(null=True, blank=True)
    start_odometer = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    end_odometer = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    distance_km = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    start_engine_hours = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    end_engine_hours = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    operating_hours = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    fuel_issued_liters = models.DecimalField(max_digits=12, decimal_places=2, default=Decimal("0.00"))
    fuel_consumed_liters = models.DecimalField(max_digits=12, decimal_places=2, default=Decimal("0.00"))
    agreed_rate = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    calculated_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    meter_rollover_authorized = models.BooleanField(default=False)
    status = models.CharField(max_length=16, choices=Status.choices, default=Status.DRAFT, db_index=True)
    idempotency_key = models.CharField(max_length=80, null=True, blank=True)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="created_trips")
    verified_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="verified_trips")
    approved_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="approved_trips")
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "fleet_vehicle_trips"
        unique_together = [("company", "trip_number"), ("company", "idempotency_key")]
        ordering = ["-start_datetime"]
        indexes = [
            models.Index(fields=["company", "vehicle", "start_datetime"], name="idx_flt_trip_cmp_v_dt"),
            models.Index(fields=["company", "status", "start_datetime"], name="idx_flt_trip_cmp_st_dt"),
        ]


class VehicleTripApproval(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    trip = models.ForeignKey(VehicleTrip, on_delete=models.CASCADE, related_name="approvals")
    actor = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True)
    stage = models.CharField(max_length=24)  # SUBMITTED|VERIFIED|APPROVED|CANCELLED
    comment = models.CharField(max_length=255, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "fleet_trip_approvals"
        ordering = ["created_at"]


class VehicleMeterReading(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE, related_name="meter_readings")
    trip = models.ForeignKey(VehicleTrip, on_delete=models.SET_NULL, null=True, blank=True)
    reading_at = models.DateTimeField(default=timezone.now)
    odometer_km = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    engine_hours = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    source = models.CharField(max_length=24, default="TRIP")  # TRIP|FUEL|MAINTENANCE|MANUAL
    recorded_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True)

    class Meta:
        db_table = "fleet_meter_readings"
        ordering = ["-reading_at"]


class VehicleFuelTransaction(models.Model):
    class Mode(models.TextChoices):
        DIRECT_FILL = "DIRECT_FILL", "Direct Vehicle Fuel Purchase"
        STOCK_PURCHASE = "STOCK_PURCHASE", "Fuel Stock Purchase (Warehouse)"
        STOCK_ISSUE = "STOCK_ISSUE", "Fuel Issued from Warehouse Stock"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="fleet_fuel_txns")
    vehicle = models.ForeignKey(Vehicle, on_delete=models.PROTECT, null=True, blank=True, related_name="fuel_transactions")
    trip = models.ForeignKey(VehicleTrip, on_delete=models.SET_NULL, null=True, blank=True)
    project = models.ForeignKey("projects.Project", on_delete=models.SET_NULL, null=True, blank=True)
    warehouse = models.ForeignKey("inventory.Warehouse", on_delete=models.SET_NULL, null=True, blank=True)
    fuel_item = models.ForeignKey("inventory.ItemMaster", on_delete=models.SET_NULL, null=True, blank=True)
    mode = models.CharField(max_length=20, choices=Mode.choices, default=Mode.DIRECT_FILL)
    fuel_date = models.DateField(db_index=True)
    fuel_type = models.CharField(max_length=16, choices=Vehicle.FuelType.choices, default=Vehicle.FuelType.DIESEL)
    quantity = models.DecimalField(max_digits=12, decimal_places=3)
    rate_per_unit = models.DecimalField(max_digits=14, decimal_places=2)
    total_amount = models.DecimalField(max_digits=18, decimal_places=2)
    engine_hours = models.DecimalField(max_digits=14, decimal_places=2, null=True, blank=True)
    odometer_km = models.DecimalField(max_digits=14, decimal_places=2, null=True, blank=True)
    fuel_efficiency_km_per_unit = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)
    receipt_no = models.CharField(max_length=64, blank=True)
    fuel_station = models.CharField(max_length=120, blank=True)
    entry_mode = models.CharField(max_length=16, default="SINGLE_ENTRY")  # SINGLE_ENTRY|DOUBLE_ENTRY
    payment_method = models.CharField(max_length=16, default="CASH")  # CASH|BANK|CREDIT
    party = models.ForeignKey("accounting.Party", on_delete=models.PROTECT, null=True, blank=True)
    voucher = models.ForeignKey("accounting.Voucher", on_delete=models.SET_NULL, null=True, blank=True)
    attachment_ref = models.CharField(max_length=255, blank=True)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "fleet_fuel_transactions"
        ordering = ["-fuel_date", "-created_at"]


class VehicleMaintenance(models.Model):
    class ServiceType(models.TextChoices):
        ROUTINE = "ROUTINE", "Routine Servicing"
        ENGINE_REPAIR = "ENGINE_REPAIR", "Engine Repair"
        TYRE = "TYRE", "Tyre Replacement"
        OIL_LUBRICANTS = "OIL_LUBRICANTS", "Oil & Lubricants"
        BATTERY = "BATTERY", "Battery"
        INSURANCE = "INSURANCE", "Insurance Renewal"
        VEHICLE_TAX = "VEHICLE_TAX", "Vehicle Tax"
        REG_RENEWAL = "REG_RENEWAL", "Registration Renewal"
        WASHING = "WASHING", "Washing & Detailing"
        PARKING_TOLL = "PARKING_TOLL", "Parking / Road Toll"
        OTHER = "OTHER", "Other Maintenance"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="fleet_maintenance")
    vehicle = models.ForeignKey(Vehicle, on_delete=models.PROTECT, related_name="maintenance_logs")
    project = models.ForeignKey("projects.Project", on_delete=models.SET_NULL, null=True, blank=True)
    service_type = models.CharField(max_length=24, choices=ServiceType.choices, default=ServiceType.ROUTINE)
    service_date = models.DateField(db_index=True)
    workshop_name = models.CharField(max_length=160, blank=True)
    party = models.ForeignKey("accounting.Party", on_delete=models.PROTECT, null=True, blank=True)
    entry_mode = models.CharField(max_length=16, default="SINGLE_ENTRY")  # SINGLE_ENTRY|DOUBLE_ENTRY
    payment_method = models.CharField(max_length=16, default="CASH")
    work_description = models.TextField()
    parts_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    labour_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    total_amount = models.DecimalField(max_digits=18, decimal_places=2)
    downtime_hours = models.DecimalField(max_digits=10, decimal_places=2, default=Decimal("0.00"))
    work_order_no = models.CharField(max_length=48, blank=True)
    status = models.CharField(max_length=20, default="POSTED")  # REQUESTED|APPROVED|IN_PROGRESS|COMPLETED|POSTED
    odometer_km = models.DecimalField(max_digits=14, decimal_places=2, null=True, blank=True)
    next_service_date = models.DateField(null=True, blank=True)
    warranty_notes = models.CharField(max_length=255, blank=True)
    voucher = models.ForeignKey("accounting.Voucher", on_delete=models.SET_NULL, null=True, blank=True)
    attachment_ref = models.CharField(max_length=255, blank=True)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "fleet_maintenance_logs"
        ordering = ["-service_date", "-created_at"]


class VehicleIncome(models.Model):
    class Category(models.TextChoices):
        VEHICLE_HIRE = "VEHICLE_HIRE", "Vehicle Hire Income"
        TRANSPORT = "TRANSPORT", "Transportation Income"
        MATERIAL_DELIVERY = "MATERIAL_DELIVERY", "Material Delivery Income"
        EXCAVATOR_HIRE = "EXCAVATOR_HIRE", "Excavator Hire Income"
        TIPPER_HIRE = "TIPPER_HIRE", "Tipper Hire Income"
        CRANE_HIRE = "CRANE_HIRE", "Crane Hire Income"
        TRACTOR_HIRE = "TRACTOR_HIRE", "Tractor Hire Income"
        PICKUP_HIRE = "PICKUP_HIRE", "Pickup Hire Income"
        LABOUR_TRANSPORT = "LABOUR_TRANSPORT", "Labour Transportation Income"
        OTHER = "OTHER", "Other Vehicle Service Income"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="fleet_incomes")
    branch = models.ForeignKey("tenancy.Branch", on_delete=models.SET_NULL, null=True, blank=True)
    fiscal_year = models.ForeignKey("tenancy.FiscalYear", on_delete=models.PROTECT, null=True, blank=True)
    vehicle = models.ForeignKey(Vehicle, on_delete=models.PROTECT, related_name="incomes")
    trip = models.ForeignKey(VehicleTrip, on_delete=models.SET_NULL, null=True, blank=True, related_name="incomes")
    rental_agreement = models.ForeignKey(VehicleRentalAgreement, on_delete=models.SET_NULL, null=True, blank=True, related_name="incomes")
    project = models.ForeignKey("projects.Project", on_delete=models.SET_NULL, null=True, blank=True)
    site = models.ForeignKey("projects.Site", on_delete=models.SET_NULL, null=True, blank=True)
    cost_center = models.ForeignKey("accounting.CostCenter", on_delete=models.SET_NULL, null=True, blank=True)
    transaction_date = models.DateField(db_index=True)
    entry_mode = models.CharField(max_length=16)  # SINGLE_ENTRY|DOUBLE_ENTRY
    payment_method = models.CharField(max_length=24)  # CASH|BANK|CREDIT|ADVANCE_ADJUST|DEPOSIT_ADJUST
    income_category = models.CharField(max_length=24, choices=Category.choices, default=Category.VEHICLE_HIRE)
    party = models.ForeignKey("accounting.Party", on_delete=models.PROTECT, null=True, blank=True, related_name="vehicle_incomes")
    counter_account = models.ForeignKey("accounting.Account", on_delete=models.PROTECT, related_name="fleet_income_debit_entries")
    income_account = models.ForeignKey("accounting.Account", on_delete=models.PROTECT, related_name="fleet_income_credit_entries")
    gross_amount = models.DecimalField(max_digits=18, decimal_places=2)
    tax_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    net_amount = models.DecimalField(max_digits=18, decimal_places=2)
    payment_reference = models.CharField(max_length=80, blank=True)
    invoice_number = models.CharField(max_length=64, blank=True)
    narration = models.TextField(blank=True)
    attachment_ref = models.CharField(max_length=255, blank=True)
    voucher = models.ForeignKey("accounting.Voucher", on_delete=models.PROTECT, related_name="fleet_incomes")
    is_reversed = models.BooleanField(default=False)
    reversal_reason = models.CharField(max_length=255, blank=True)
    reversed_voucher = models.ForeignKey("accounting.Voucher", on_delete=models.SET_NULL, null=True, blank=True, related_name="+")
    idempotency_key = models.CharField(max_length=80, null=True, blank=True)
    entered_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "fleet_vehicle_incomes"
        unique_together = [("company", "idempotency_key")]
        ordering = ["-transaction_date", "-created_at"]


class VehicleExpense(models.Model):
    class Category(models.TextChoices):
        VEHICLE_HIRE = "VEHICLE_HIRE", "Rented Vehicle Hire Expense"
        TRANSPORT = "TRANSPORT", "Transportation Expense"
        DRIVER_CHARGES = "DRIVER_CHARGES", "Driver / Operator Charges"
        FUEL = "FUEL", "Fuel Expense"
        REPAIR_MAINT = "REPAIR_MAINT", "Vehicle Repair & Maintenance"
        MOBILIZATION = "MOBILIZATION", "Mobilization Charges"
        DEMOBILIZATION = "DEMOBILIZATION", "Demobilization Charges"
        WAITING = "WAITING", "Waiting Charges"
        OVERTIME = "OVERTIME", "Overtime Charges"
        INSURANCE_TAX = "INSURANCE_TAX", "Insurance & Vehicle Tax"
        OTHER = "OTHER", "Other Operating Expense"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="fleet_expenses")
    branch = models.ForeignKey("tenancy.Branch", on_delete=models.SET_NULL, null=True, blank=True)
    fiscal_year = models.ForeignKey("tenancy.FiscalYear", on_delete=models.PROTECT, null=True, blank=True)
    vehicle = models.ForeignKey(Vehicle, on_delete=models.PROTECT, related_name="expenses")
    trip = models.ForeignKey(VehicleTrip, on_delete=models.SET_NULL, null=True, blank=True, related_name="expenses")
    rental_agreement = models.ForeignKey(VehicleRentalAgreement, on_delete=models.SET_NULL, null=True, blank=True, related_name="expenses")
    project = models.ForeignKey("projects.Project", on_delete=models.SET_NULL, null=True, blank=True)
    site = models.ForeignKey("projects.Site", on_delete=models.SET_NULL, null=True, blank=True)
    cost_center = models.ForeignKey("accounting.CostCenter", on_delete=models.SET_NULL, null=True, blank=True)
    cost_code = models.ForeignKey("projects.CostCode", on_delete=models.SET_NULL, null=True, blank=True)
    transaction_date = models.DateField(db_index=True)
    entry_mode = models.CharField(max_length=16)  # SINGLE_ENTRY|DOUBLE_ENTRY
    payment_method = models.CharField(max_length=24)  # CASH|BANK|CREDIT|ADVANCE_ADJUST|DEPOSIT_ADJUST
    expense_category = models.CharField(max_length=24, choices=Category.choices, default=Category.VEHICLE_HIRE)
    hire_basis = models.CharField(max_length=16, blank=True)
    quantity = models.DecimalField(max_digits=14, decimal_places=3, default=Decimal("1.000"))
    rate = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    party = models.ForeignKey("accounting.Party", on_delete=models.PROTECT, null=True, blank=True, related_name="vehicle_expenses")
    expense_account = models.ForeignKey("accounting.Account", on_delete=models.PROTECT, related_name="fleet_expense_debit_entries")
    counter_account = models.ForeignKey("accounting.Account", on_delete=models.PROTECT, related_name="fleet_expense_credit_entries")
    gross_amount = models.DecimalField(max_digits=18, decimal_places=2)
    tax_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    tds_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    net_amount = models.DecimalField(max_digits=18, decimal_places=2)
    supplier_invoice_no = models.CharField(max_length=64, blank=True)
    narration = models.TextField(blank=True)
    attachment_ref = models.CharField(max_length=255, blank=True)
    voucher = models.ForeignKey("accounting.Voucher", on_delete=models.PROTECT, related_name="fleet_expenses")
    is_reversed = models.BooleanField(default=False)
    reversal_reason = models.CharField(max_length=255, blank=True)
    reversed_voucher = models.ForeignKey("accounting.Voucher", on_delete=models.SET_NULL, null=True, blank=True, related_name="+")
    idempotency_key = models.CharField(max_length=80, null=True, blank=True)
    entered_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "fleet_vehicle_expenses"
        unique_together = [("company", "idempotency_key")]
        ordering = ["-transaction_date", "-created_at"]


class VehicleAdvance(models.Model):
    class Kind(models.TextChoices):
        RENTAL_SUPPLIER_ADV = "RENTAL_SUPPLIER_ADV", "Rental Advance Paid to Owner"
        CUSTOMER_HIRE_ADV = "CUSTOMER_HIRE_ADV", "Customer Hire Advance Received"
        DRIVER_ADVANCE = "DRIVER_ADVANCE", "Driver Allowance / Trip Advance"
        FUEL_ADVANCE = "FUEL_ADVANCE", "Fuel Advance"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="fleet_advances")
    vehicle = models.ForeignKey(Vehicle, on_delete=models.PROTECT, null=True, blank=True)
    rental_agreement = models.ForeignKey(VehicleRentalAgreement, on_delete=models.SET_NULL, null=True, blank=True)
    driver = models.ForeignKey(VehicleDriver, on_delete=models.SET_NULL, null=True, blank=True)
    party = models.ForeignKey("accounting.Party", on_delete=models.PROTECT, null=True, blank=True)
    kind = models.CharField(max_length=24, choices=Kind.choices)
    advance_date = models.DateField()
    amount = models.DecimalField(max_digits=18, decimal_places=2)
    settled_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    voucher = models.ForeignKey("accounting.Voucher", on_delete=models.PROTECT, related_name="fleet_advances")
    notes = models.CharField(max_length=255, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "fleet_advances"
        ordering = ["-advance_date"]


class VehicleSecurityDeposit(models.Model):
    class Direction(models.TextChoices):
        PAID_TO_OWNER = "PAID_TO_OWNER", "Rental Security Deposit Paid (Asset)"
        RECEIVED_FROM_CUSTOMER = "RECEIVED_FROM_CUSTOMER", "Customer Security Deposit Received (Liability)"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="fleet_deposits")
    direction = models.CharField(max_length=28, choices=Direction.choices)
    vehicle = models.ForeignKey(Vehicle, on_delete=models.PROTECT, related_name="security_deposits")
    rental_agreement = models.ForeignKey(VehicleRentalAgreement, on_delete=models.SET_NULL, null=True, blank=True)
    party = models.ForeignKey("accounting.Party", on_delete=models.PROTECT, related_name="vehicle_deposits")
    deposit_date = models.DateField()
    amount = models.DecimalField(max_digits=18, decimal_places=2)
    refunded_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    deposit_account = models.ForeignKey("accounting.Account", on_delete=models.PROTECT, related_name="fleet_deposit_accounts")
    cash_bank_account = models.ForeignKey("accounting.Account", on_delete=models.PROTECT, related_name="fleet_deposit_counter_accounts")
    voucher = models.ForeignKey("accounting.Voucher", on_delete=models.PROTECT, related_name="fleet_deposits")
    refund_voucher = models.ForeignKey("accounting.Voucher", on_delete=models.SET_NULL, null=True, blank=True, related_name="fleet_deposit_refunds")
    status = models.CharField(max_length=16, default="HELD")  # HELD|PARTIAL_REFUND|REFUNDED|FORFEITED
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "fleet_security_deposits"
        ordering = ["-deposit_date"]


class VehicleCustomerBilling(models.Model):
    """Links hired-out vehicle invoices & customer receipts against Party OpenItem balances."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    vehicle_income = models.OneToOneField(VehicleIncome, on_delete=models.CASCADE, related_name="customer_billing")
    party = models.ForeignKey("accounting.Party", on_delete=models.PROTECT)
    invoice_no = models.CharField(max_length=64)
    total_amount = models.DecimalField(max_digits=18, decimal_places=2)
    received_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    status = models.CharField(max_length=16, default="OPEN")  # OPEN|PARTIAL|SETTLED

    class Meta:
        db_table = "fleet_customer_billings"
        unique_together = [("company", "invoice_no")]


class VehicleSupplierBilling(models.Model):
    """Links rented-in / maintenance supplier bills & payments against Party OpenItem balances."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    vehicle_expense = models.OneToOneField(VehicleExpense, on_delete=models.CASCADE, related_name="supplier_billing")
    party = models.ForeignKey("accounting.Party", on_delete=models.PROTECT)
    supplier_invoice_no = models.CharField(max_length=64)
    total_amount = models.DecimalField(max_digits=18, decimal_places=2)
    paid_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    status = models.CharField(max_length=16, default="OPEN")  # OPEN|PARTIAL|SETTLED

    class Meta:
        db_table = "fleet_supplier_billings"
        unique_together = [("company", "party", "supplier_invoice_no")]


class VehicleCostAllocation(models.Model):
    """Internal project cost allocation for company-owned vehicles (never generates external revenue)."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="fleet_cost_allocations")
    vehicle = models.ForeignKey(Vehicle, on_delete=models.PROTECT, related_name="cost_allocations")
    trip = models.ForeignKey(VehicleTrip, on_delete=models.SET_NULL, null=True, blank=True)
    project = models.ForeignKey("projects.Project", on_delete=models.PROTECT, related_name="vehicle_cost_allocations")
    site = models.ForeignKey("projects.Site", on_delete=models.SET_NULL, null=True, blank=True)
    cost_center = models.ForeignKey("accounting.CostCenter", on_delete=models.SET_NULL, null=True, blank=True)
    cost_code = models.ForeignKey("projects.CostCode", on_delete=models.SET_NULL, null=True, blank=True)
    allocation_date = models.DateField()
    basis = models.CharField(max_length=16, default="HOURS")  # HOURS|KM|DAILY|FIXED
    quantity = models.DecimalField(max_digits=12, decimal_places=2)
    rate = models.DecimalField(max_digits=14, decimal_places=2)
    allocated_amount = models.DecimalField(max_digits=18, decimal_places=2)
    wip_debit_account = models.ForeignKey("accounting.Account", on_delete=models.PROTECT, related_name="fleet_alloc_debits")
    recovery_credit_account = models.ForeignKey("accounting.Account", on_delete=models.PROTECT, related_name="fleet_alloc_credits")
    voucher = models.ForeignKey("accounting.Voucher", on_delete=models.PROTECT, related_name="fleet_cost_allocations")
    notes = models.CharField(max_length=255, blank=True)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "fleet_cost_allocations"
        ordering = ["-allocation_date"]


class VehicleAuditEvent(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    vehicle = models.ForeignKey(Vehicle, on_delete=models.SET_NULL, null=True, blank=True)
    actor = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True)
    action = models.CharField(max_length=64, db_index=True)
    entity_type = models.CharField(max_length=64)
    entity_id = models.CharField(max_length=64)
    metadata = models.JSONField(default=dict, blank=True, encoder=DjangoJSONEncoder)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "fleet_audit_events"
        ordering = ["-created_at"]


class VehicleStatusHistory(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE, related_name="status_history")
    previous_status = models.CharField(max_length=24, blank=True)
    new_status = models.CharField(max_length=24)
    reason = models.CharField(max_length=255, blank=True)
    changed_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True)
    changed_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "fleet_status_history"
        ordering = ["-changed_at"]


class VehicleMaintenanceSchedule(models.Model):
    class Frequency(models.TextChoices):
        EVERY_KM = "EVERY_KM", "Every Specified KM"
        EVERY_HOUR = "EVERY_HOUR", "Every Specified Engine Hour"
        MONTHLY = "MONTHLY", "Monthly"
        QUARTERLY = "QUARTERLY", "Quarterly"
        ANNUAL = "ANNUAL", "Annual"
        CUSTOM = "CUSTOM", "Custom Period"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="fleet_maint_schedules")
    vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE, related_name="maintenance_schedules")
    service_title = models.CharField(max_length=160)
    frequency = models.CharField(max_length=16, choices=Frequency.choices, default=Frequency.EVERY_KM)
    interval_km = models.DecimalField(max_digits=12, decimal_places=2, default=Decimal("0.00"))
    interval_hours = models.DecimalField(max_digits=12, decimal_places=2, default=Decimal("0.00"))
    next_due_km = models.DecimalField(max_digits=14, decimal_places=2, null=True, blank=True)
    next_due_hours = models.DecimalField(max_digits=14, decimal_places=2, null=True, blank=True)
    next_due_date = models.DateField(null=True, blank=True)
    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "fleet_maintenance_schedules"
        ordering = ["next_due_date", "vehicle"]


class RentalSettlement(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="fleet_rental_settlements")
    agreement = models.ForeignKey(VehicleRentalAgreement, on_delete=models.PROTECT, related_name="settlements")
    settlement_no = models.CharField(max_length=48)
    period_start = models.DateField()
    period_end = models.DateField()
    approved_trip_count = models.PositiveIntegerField(default=0)
    eligible_quantity = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    base_amount = models.DecimalField(max_digits=18, decimal_places=2)
    additions_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    deductions_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    net_amount = models.DecimalField(max_digits=18, decimal_places=2)
    voucher = models.ForeignKey("accounting.Voucher", on_delete=models.SET_NULL, null=True, blank=True)
    status = models.CharField(max_length=20, default="POSTED")
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "fleet_rental_settlements"
        unique_together = [("company", "settlement_no")]
        ordering = ["-period_end"]


class TripCostCalculation(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    trip = models.OneToOneField(VehicleTrip, on_delete=models.CASCADE, related_name="cost_calculation")
    rate_basis = models.CharField(max_length=24, default="AGREEMENT")
    billable_units = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    unit_rate = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    gross_revenue = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    estimated_fuel_cost = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    estimated_driver_cost = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    net_margin = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    calculated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "fleet_trip_cost_calculations"


class VehicleDriverSettlement(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="fleet_driver_settlements")
    advance = models.ForeignKey(VehicleAdvance, on_delete=models.PROTECT, related_name="settlements")
    driver = models.ForeignKey(VehicleDriver, on_delete=models.PROTECT, related_name="advance_settlements")
    vehicle = models.ForeignKey(Vehicle, on_delete=models.PROTECT, null=True, blank=True)
    settlement_date = models.DateField()
    fuel_expense = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    trip_expense = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    road_toll_expense = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    allowance_expense = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    maintenance_expense = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    total_expensed = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    cash_returned = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    voucher = models.ForeignKey("accounting.Voucher", on_delete=models.PROTECT)
    notes = models.CharField(max_length=255, blank=True)
    settled_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "fleet_driver_settlements"
        ordering = ["-settlement_date"]


class FleetConfiguration(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.OneToOneField("tenancy.Company", on_delete=models.CASCADE, related_name="fleet_config")
    vehicle_categories = models.JSONField(default=list, blank=True)
    income_categories = models.JSONField(default=list, blank=True)
    expense_categories = models.JSONField(default=list, blank=True)
    fuel_accounting_method = models.CharField(max_length=24, default="DIRECT_EXPENSE")  # DIRECT_EXPENSE|INVENTORY
    require_trip_approval_before_billing = models.BooleanField(default=True)
    require_attachment_on_cash_expense = models.BooleanField(default=False)
    allow_single_entry_rented_cash = models.BooleanField(default=True)
    allow_odometer_rollover_override = models.BooleanField(default=True)
    approval_workflows = models.JSONField(default=dict, blank=True)
    gl_mappings = models.JSONField(default=dict, blank=True)
    updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "fleet_configurations"


class FleetReportRun(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="fleet_report_runs")
    report_code = models.CharField(max_length=48, db_index=True)
    report_format = models.CharField(max_length=12, default="JSON")  # JSON|PDF|XLSX|CSV
    filters_json = models.JSONField(default=dict, blank=True, encoder=DjangoJSONEncoder)
    row_count = models.PositiveIntegerField(default=0)
    run_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "fleet_report_runs"
        ordering = ["-created_at"]

