-- Migration: 004_relax_odometer_and_trip_precision.sql
-- Purpose: Align schema with enhanced API allowing trip-only entries
-- Changes:
--  - Make odometer nullable (trip-only logs permitted)
--  - Change trip_distance to DECIMAL(10,3) to allow fractional distances

BEGIN;

-- Allow trip-only entries by making odometer nullable
ALTER TABLE fuel_logs ALTER COLUMN odometer DROP NOT NULL;

-- Allow fractional trip distances
ALTER TABLE fuel_logs
  ALTER COLUMN trip_distance TYPE DECIMAL(10,3)
  USING CASE WHEN trip_distance IS NULL THEN NULL ELSE trip_distance::DECIMAL(10,3) END;

-- Ensure the distance_required_check still exists; recreate defensively with correct semantics
DO $$ 
BEGIN
  IF EXISTS (
    SELECT 1 FROM pg_constraint WHERE conname = 'distance_required_check'
  ) THEN
    ALTER TABLE fuel_logs DROP CONSTRAINT distance_required_check;
  END IF;
  ALTER TABLE fuel_logs ADD CONSTRAINT distance_required_check
    CHECK ((trip_distance IS NOT NULL AND trip_distance > 0) OR 
           (odometer IS NOT NULL AND odometer > 0));
END $$;

COMMIT;

