<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--
  WiringMapper — M4 유틸리티 배선(PostGIS). 트렌치 POINT KNN(<->), 최단 배선 ST_MakeLine/ST_Distance.
  kind: power|network|plumbing|water|air|gas → 트렌치 공급 컬럼 매핑.
  shortestPath 반환: lineJson(GeoJSON LineString) + lengthM + assumed — 백엔드가 coords 파싱.
-->
<mapper namespace="com.zioinfo.kintex.module.m4.mapper.WiringMapper">

    <!-- kind → 공급 조건 SQL 조각. -->
    <sql id="supplyCondition">
        <choose>
            <when test="kind == 'power'">t.supply_power = true</when>
            <when test="kind == 'network'">t.supply_network = true</when>
            <when test="kind == 'plumbing' or kind == 'water'">t.supply_water = true</when>
            <when test="kind == 'air'">t.supply_air = true</when>
            <when test="kind == 'gas'">t.supply_gas = true</when>
            <otherwise>true</otherwise>
        </choose>
    </sql>

    <!-- 부스 중심 기준 최근접 트렌치(kind 공급 가능) — KNN 정렬 상위 5개. -->
    <select id="findNearestTrenches" resultType="map">
        SELECT t.id            AS "trenchId",
               ST_X(t.geom)    AS "x",
               ST_Y(t.geom)    AS "y",
               ST_Distance(t.geom, c.centroid) AS "distanceM",
               t.is_assumed    AS "assumed"
        FROM trench t
        CROSS JOIN (SELECT ST_Centroid(geom) AS centroid FROM booth WHERE id = #{boothId}) c
        WHERE t.hall_id = #{hallId}
          AND <include refid="supplyCondition"/>
        ORDER BY t.geom <![CDATA[<->]]> c.centroid
        LIMIT 5
    </select>

    <!-- 단말(fromX,fromY) → 최근접 공급 트렌치 최단 직선 경로 + 길이. -->
    <select id="shortestPath" resultType="map">
        SELECT ST_AsGeoJSON(
                   ST_MakeLine(t.geom, ST_SetSRID(ST_MakePoint(#{fromX}, #{fromY}), 0))
               )                                                              AS "lineJson",
               ST_Distance(t.geom, ST_SetSRID(ST_MakePoint(#{fromX}, #{fromY}), 0)) AS "lengthM",
               t.is_assumed                                                   AS "assumed"
        FROM trench t
        WHERE t.hall_id = #{hallId}
          AND <include refid="supplyCondition"/>
        ORDER BY t.geom <![CDATA[<->]]> ST_SetSRID(ST_MakePoint(#{fromX}, #{fromY}), 0)
        LIMIT 1
    </select>

    <!-- 홀 트렌치가 가정 그리드인지(실측 미확보) 여부. -->
    <select id="isAssumedTrench" resultType="boolean">
        SELECT is_assumed_trench
        FROM hall
        WHERE id = #{hallId}
    </select>

</mapper>
