-- Migration: 002_enhance_fuel_logs_schema.sql
-- Enhance fuel_logs schema with new fields and constraints

BEGIN;

-- Add new columns (nullable initially for backfill)
ALTER TABLE fuel_logs ADD COLUMN IF NOT EXISTS trip_distance INTEGER;
ALTER TABLE fuel_logs ADD COLUMN IF NOT EXISTS fuel_type VARCHAR(20);
ALTER TABLE fuel_logs ADD COLUMN IF NOT EXISTS fuel_grade VARCHAR(10);
ALTER TABLE fuel_logs ADD COLUMN IF NOT EXISTS fuel_units DECIMAL(8,3);
ALTER TABLE fuel_logs ADD COLUMN IF NOT EXISTS cost_per_unit DECIMAL(6,3);
ALTER TABLE fuel_logs ADD COLUMN IF NOT EXISTS location_data JSONB;
ALTER TABLE fuel_logs ADD COLUMN IF NOT EXISTS date_time TIMESTAMP WITH TIME ZONE;

-- Backfill existing data
UPDATE fuel_logs SET 
  fuel_type = 'gasoline',
  fuel_units = gallons,
  cost_per_unit = price_per_gallon,
  date_time = (date::timestamp AT TIME ZONE 'UTC') + interval '12 hours'
WHERE fuel_type IS NULL;

-- Set NOT NULL and defaults where applicable
ALTER TABLE fuel_logs ALTER COLUMN fuel_type SET NOT NULL;
ALTER TABLE fuel_logs ALTER COLUMN fuel_type SET DEFAULT 'gasoline';

-- Check constraints
DO $$ 
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM pg_constraint WHERE conname = 'fuel_type_check'
  ) THEN
    ALTER TABLE fuel_logs ADD CONSTRAINT fuel_type_check 
      CHECK (fuel_type IN ('gasoline', 'diesel', 'electric'));
  END IF;
END $$;

-- Either trip_distance OR odometer required (> 0)
DO $$ 
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM pg_constraint WHERE conname = 'distance_required_check'
  ) THEN
    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 IF;
END $$;

-- Fuel grade validation trigger
CREATE OR REPLACE FUNCTION validate_fuel_grade()
RETURNS TRIGGER AS $$
BEGIN
  -- Gasoline
  IF NEW.fuel_type = 'gasoline' AND NEW.fuel_grade IS NOT NULL AND 
     NEW.fuel_grade NOT IN ('87', '88', '89', '91', '93') THEN
    RAISE EXCEPTION 'Invalid fuel grade % for gasoline', NEW.fuel_grade;
  END IF;

  -- Diesel
  IF NEW.fuel_type = 'diesel' AND NEW.fuel_grade IS NOT NULL AND 
     NEW.fuel_grade NOT IN ('#1', '#2') THEN
    RAISE EXCEPTION 'Invalid fuel grade % for diesel', NEW.fuel_grade;
  END IF;

  -- Electric: no grade allowed
  IF NEW.fuel_type = 'electric' AND NEW.fuel_grade IS NOT NULL THEN
    RAISE EXCEPTION 'Electric fuel type cannot have a grade';
  END IF;

  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

DO $$
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM pg_trigger WHERE tgname = 'fuel_grade_validation_trigger'
  ) THEN
    CREATE TRIGGER fuel_grade_validation_trigger
      BEFORE INSERT OR UPDATE ON fuel_logs
      FOR EACH ROW EXECUTE FUNCTION validate_fuel_grade();
  END IF;
END;
$$;

-- Indexes for performance
CREATE INDEX IF NOT EXISTS idx_fuel_logs_fuel_type ON fuel_logs(fuel_type);
CREATE INDEX IF NOT EXISTS idx_fuel_logs_date_time ON fuel_logs(date_time);

COMMIT;

