-- Fix geometry column type in tb_map_sheet_learn_data_geom table
-- The table was incorrectly created with 'bytea' type instead of 'geometry' type

-- 1. First ensure PostGIS is enabled
CREATE EXTENSION IF NOT EXISTS postgis;

-- 2. Check if column needs to be recreated (only if it's bytea type)
-- Only clear data if the column type is incorrect and needs conversion
DO $$
BEGIN
    -- Only delete data if geom column exists and is bytea type
    IF EXISTS (
        SELECT 1 FROM information_schema.columns 
        WHERE table_name = 'tb_map_sheet_learn_data_geom' 
        AND column_name = 'geom' 
        AND data_type = 'bytea'
    ) THEN
        DELETE FROM public.tb_map_sheet_learn_data_geom WHERE geom IS NOT NULL;
        RAISE NOTICE 'Cleared incorrect bytea geometry data for conversion';
    ELSE
        RAISE NOTICE 'Geometry column is already correct type, skipping data deletion';
    END IF;
END $$;

-- 3. Drop and recreate the geom column with correct PostGIS geometry type (only if needed)
ALTER TABLE public.tb_map_sheet_learn_data_geom DROP COLUMN IF EXISTS geom;
ALTER TABLE public.tb_map_sheet_learn_data_geom ADD COLUMN geom geometry(Polygon, 5186);

-- 4. Create spatial index for performance
CREATE INDEX IF NOT EXISTS idx_tb_map_sheet_learn_data_geom_spatial 
ON public.tb_map_sheet_learn_data_geom USING GIST (geom);

-- 5. Update column comment
COMMENT ON COLUMN public.tb_map_sheet_learn_data_geom.geom IS 'PostGIS geometry 정보 (Polygon, EPSG:5186)';

-- 6. Verify the column type is correct
SELECT column_name, data_type, udt_name 
FROM information_schema.columns 
WHERE table_name = 'tb_map_sheet_learn_data_geom' AND column_name = 'geom';

SELECT 'Geometry column type fixed successfully' as message;