-- Migration to add PostGIS geometry support to sites table
-- Run this after enabling PostGIS extension

-- Add PostGIS geometry column for spatial operations
ALTER TABLE sites ADD COLUMN IF NOT EXISTS location_geometry geometry(Point, 4326);

-- Create spatial index for efficient queries
CREATE INDEX IF NOT EXISTS idx_site_geometry ON sites USING GIST (location_geometry);

-- Update existing records to populate geometry from lat/lng
UPDATE sites
SET location_geometry = ST_GeogFromText('POINT(' || longitude || ' ' || latitude || ')')::geometry
WHERE latitude IS NOT NULL
  AND longitude IS NOT NULL
  AND location_geometry IS NULL;

-- Add constraint to ensure geometry is valid
ALTER TABLE sites ADD CONSTRAINT check_location_geometry
    CHECK (ST_IsValid(location_geometry) OR location_geometry IS NULL);

-- Add comment for documentation
COMMENT ON COLUMN sites.location_geometry IS 'PostGIS geometry field for spatial operations (SRID 4326 = WGS84)';
