package qc

import (
	"encoding/json"
	"fmt"
	"net/http"
	"verofy-backend/models"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func GraphConnectivityRoute(router *gin.Engine, db *gorm.DB, schema, segmentTable, mapIDCol, zoneCol, idCol, qcFlagCol string) {
	router.GET("/api/qc/connectivity", func(c *gin.Context) {
		mapID := c.Query("map_id")
		zone := c.Query("zone")
		if mapID == "" || zone == "" {
			c.JSON(http.StatusBadRequest, gin.H{"error": "map_id and zone are required"})
			return
		}

		var segments []models.SegmentGeoJSON
		table := fmt.Sprintf("%s.%s", schema, segmentTable)

		db.Table(table).Select(fmt.Sprintf("id_0, %s, segment_type, segment_status, %s, protection_status, %s, ST_AsGeoJSON(ST_Transform(geom, 4326))::json AS geometry", mapIDCol, idCol, qcFlagCol)).
			Where(fmt.Sprintf("%s = ? AND %s = ?", mapIDCol, zoneCol), mapID, zone).
			Find(&segments)

		features := []map[string]interface{}{}
		for _, s := range segments {
			var geometry interface{}
			if err := json.Unmarshal(s.Geometry, &geometry); err == nil {
				features = append(features, map[string]interface{}{
					"type":     "Feature",
					"geometry": geometry,
					"properties": map[string]interface{}{
						"id_0":              s.ID0,
						"mapid":             s.MapID,
						"segment_type":      s.SegmentType,
						"segment_status":    s.SegmentStatus,
						"id":                s.ID,
						"protection_status": s.ProtectionStatus,
					},
				})
			}
		}

		c.JSON(http.StatusOK, map[string]interface{}{
			"type":     "FeatureCollection",
			"features": features,
		})
	})
}
