<?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">
<mapper namespace="vehicle">

  <sql id="vehicleSearchCondition">
    <if test="keyword != null and keyword != ''">
      AND (VEHICLE_NUMBER ILIKE '%' || #{keyword} || '%'
           OR DRIVER_NAME ILIKE '%' || #{keyword} || '%'
           OR VEHICLE_TYPE ILIKE '%' || #{keyword} || '%')
    </if>
    <if test="status != null and status != ''">
      AND STATUS = #{status}
    </if>
  </sql>

  <select id="getVehicleList" parameterType="map" resultType="map">
    SELECT *

    FROM VEHICLES

    WHERE 1=1
    <include refid="common.companyCodeFilter"/>
    <include refid="vehicleSearchCondition"/>

    <include refid="common.dynamicOrderBy"/>
    <include refid="common.pagination"/>
  </select>

  <select id="getVehicleListCnt" parameterType="map" resultType="int">
    SELECT COUNT(*)

    FROM VEHICLES

    WHERE 1=1
    <include refid="common.companyCodeFilter"/>
    <include refid="vehicleSearchCondition"/>
  </select>

  <select id="getVehicleInfo" parameterType="map" resultType="map">
    SELECT *

    FROM VEHICLES

    WHERE ID = #{id}
    <include refid="common.companyCodeFilter"/>
  </select>

  <insert id="insertVehicle" parameterType="map" useGeneratedKeys="true" keyProperty="id">
    INSERT INTO VEHICLES (
        VEHICLE_NUMBER
        , VEHICLE_TYPE
        , USER_ID
        , DRIVER_NAME
        , DRIVER_PHONE
        , BRANCH_NAME
        , STATUS
        , COMPANY_CODE
        , CREATED_DATE
        , UPDATED_DATE
    ) VALUES (
        #{vehicle_number}
        , #{vehicle_type}
        , #{user_id}
        , #{driver_name}
        , #{driver_phone}
        , #{branch_name}
        , COALESCE(#{status}, 'off')
        , #{company_code}
        , NOW()
        , NOW()
    )
  </insert>

  <update id="updateVehicle" parameterType="map">
    UPDATE VEHICLES

    SET
        VEHICLE_NUMBER = COALESCE(#{vehicle_number}, VEHICLE_NUMBER)
        , VEHICLE_TYPE   = COALESCE(#{vehicle_type},   VEHICLE_TYPE)
        , DRIVER_NAME    = COALESCE(#{driver_name},     DRIVER_NAME)
        , DRIVER_PHONE   = COALESCE(#{driver_phone},    DRIVER_PHONE)
        , BRANCH_NAME    = COALESCE(#{branch_name},     BRANCH_NAME)
        , STATUS         = COALESCE(#{status},         STATUS)
        , UPDATED_DATE     = NOW()

    WHERE ID = #{id}
    <include refid="common.companyCodeFilter"/>
  </update>

  <delete id="deleteVehicle" parameterType="map">
    DELETE FROM VEHICLES

    WHERE ID = #{id}
    <include refid="common.companyCodeFilter"/>
  </delete>

  <!-- 차량 위치 목록 조회 -->
  <select id="getVehicleLocationList" parameterType="map" resultType="map">
    SELECT *

    FROM VEHICLE_LOCATIONS

    ORDER BY LAST_UPDATE DESC
  </select>

  <!-- 차량 위치 이동 (DB 함수 호출) -->
  <select id="moveVehicles" parameterType="map" resultType="map">
    SELECT MOVE_VEHICLES()
  </select>

</mapper>
