-- Add number_of_travelers column to trips table
ALTER TABLE trips ADD COLUMN IF NOT EXISTS number_of_travelers integer;

-- Add title and updated_at to trip_days
ALTER TABLE trip_days ADD COLUMN IF NOT EXISTS title text;
ALTER TABLE trip_days ADD COLUMN IF NOT EXISTS updated_at timestamp with time zone DEFAULT now();

-- Add time_of_day and updated_at to trip_places
ALTER TABLE trip_places ADD COLUMN IF NOT EXISTS time_of_day text;
ALTER TABLE trip_places ADD COLUMN IF NOT EXISTS updated_at timestamp with time zone DEFAULT now();

-- Add triggers for updated_at if they don't exist
CREATE OR REPLACE FUNCTION update_updated_at_column()
RETURNS TRIGGER AS $$
BEGIN
    NEW.updated_at = now();
    RETURN NEW;
END;
$$ language 'plpgsql';

DO $$
BEGIN
    IF NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname = 'update_trips_updated_at') THEN
        CREATE TRIGGER update_trips_updated_at
        BEFORE UPDATE ON trips
        FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
    END IF;

    IF NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname = 'update_trip_days_updated_at') THEN
        CREATE TRIGGER update_trip_days_updated_at
        BEFORE UPDATE ON trip_days
        FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
    END IF;

    IF NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname = 'update_trip_places_updated_at') THEN
        CREATE TRIGGER update_trip_places_updated_at
        BEFORE UPDATE ON trip_places
        FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
    END IF;
END $$;
