<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="kr.itn.itnhub.org.OrganizationMapper">

  <sql id="columns">
    id, org_no, org_name, channel_slug,
    dept_name, manager_name, manager_title, manager_phone, manager_email,
    channel_id_mj, channel_id_law
  </sql>

  <select id="findAll" resultType="kr.itn.itnhub.org.Organization">
    select <include refid="columns"/>
    from organization
    order by org_no asc, org_name asc
  </select>

  <select id="findById" resultType="kr.itn.itnhub.org.Organization">
    select <include refid="columns"/>
    from organization
    where id = #{id}
  </select>

  <!--
    시드 upsert. coalesce(기존값, 새값) 순서가 핵심이다.
    기존값이 있으면 그대로 두고 비어 있을 때만 시트 값으로 채운다.
    반대로 쓰면 사람이 웹에서 고친 값이 시트 값으로 되돌아간다.
  -->
  <insert id="upsertBySeed" parameterType="kr.itn.itnhub.org.Organization">
    insert into organization
      (org_no, org_name, channel_slug,
       dept_name, manager_name, manager_title, manager_phone, manager_email)
    values
      (#{orgNo}, #{orgName}, #{channelSlug},
       #{deptName}, #{managerName}, #{managerTitle}, #{managerPhone}, #{managerEmail})
    on conflict (org_no, org_name) do update set
      channel_slug  = excluded.channel_slug,
      dept_name     = coalesce(organization.dept_name,     excluded.dept_name),
      manager_name  = coalesce(organization.manager_name,  excluded.manager_name),
      manager_title = coalesce(organization.manager_title, excluded.manager_title),
      manager_phone = coalesce(organization.manager_phone, excluded.manager_phone),
      manager_email = coalesce(organization.manager_email, excluded.manager_email),
      updated_at    = now()
  </insert>

  <update id="updateContact" parameterType="kr.itn.itnhub.org.Organization">
    update organization set
      dept_name     = #{deptName},
      manager_name  = #{managerName},
      manager_title = #{managerTitle},
      manager_phone = #{managerPhone},
      manager_email = #{managerEmail},
      updated_at    = now()
    where id = #{id}
  </update>

  <update id="updateChannelIdMj">
    update organization set
      channel_id_mj = #{channelId},
      updated_at    = now()
    where id = #{id}
  </update>

  <update id="updateChannelIdLaw">
    update organization set
      channel_id_law = #{channelId},
      updated_at     = now()
    where id = #{id}
  </update>

</mapper>
