-- 02_fuel_fills_dedupe_join.sql — fleetfuel · fix v_fuel_fills row fan-out
-- ─────────────────────────────────────────────────────────────────────────────
-- A plate can map to more than one tracksolid.devices row (a vehicle re-fitted
-- with a new tracker keeps the same number plate), so the migration-01 plain
-- LEFT JOIN produced multiple rows per fill and double-counted litres / spend
-- (v_fuel_fills had ~3345 rows for ~1888 live records). Replace the join with a
-- LATERAL ... LIMIT 1 that picks exactly one device per fill (prefer enabled,
-- most-recently-updated), so each fill yields a single row. Columns unchanged,
-- so dependent reporting.v_fuel_efficiency stays valid. Idempotent.
-- ─────────────────────────────────────────────────────────────────────────────

CREATE OR REPLACE VIEW reporting.v_fuel_fills AS
 SELECT r.id,
        r.record_datetime,
        r.record_datetime::date AS fuel_date,
        r.plate,
        d.vehicle_number,
        d.cost_centre,
        d.assigned_city,
        d.assigned_driver,
        d.imei,
        r.department,
        r.driver,
        r.liters,
        r.amount,
        r.fuel_type,
        r.odometer
   FROM fuel.records r
   LEFT JOIN LATERAL (
        SELECT dv.vehicle_number, dv.cost_centre, dv.assigned_city,
               dv.driver_name AS assigned_driver, dv.imei
          FROM tracksolid.devices dv
         WHERE r.plate IS NOT NULL
           AND fuel.norm_plate(dv.vehicle_number) = r.plate
         ORDER BY dv.enabled_flag DESC NULLS LAST, dv.updated_at DESC NULLS LAST
         LIMIT 1
   ) d ON true
  WHERE r.deleted_at IS NULL;
