package com.zioinfo.kintex.system.program;

import org.apache.ibatis.annotations.*;

import java.util.List;
import java.util.Map;

/** 프로그램(화면) 매퍼(sys_program). 테넌트 스코프. */
@Mapper
public interface ProgramMapper {

    @Select("""
            <script>
            SELECT id, program_name AS "programName", program_type AS "programType",
                   program_url AS "programUrl", category, use_yn AS "useYn"
            FROM sys_program
            <where>
              AND tenant_id = #{tenantId}
              <if test="keyword != null and keyword != ''">
                AND (program_name ILIKE '%'||#{keyword}||'%' OR program_url ILIKE '%'||#{keyword}||'%')
              </if>
              <if test="category != null and category != ''">AND category = #{category}</if>
            </where>
            ORDER BY category NULLS FIRST, program_name
            </script>
            """)
    List<Map<String, Object>> findAll(@Param("tenantId") String tenantId,
                                      @Param("keyword") String keyword, @Param("category") String category);

    @Insert("INSERT INTO sys_program (tenant_id, id, program_name, program_type, program_url, category, use_yn) "
            + "VALUES (#{tenantId}, #{id}, #{programName}, COALESCE(#{programType},'SCREEN'), #{programUrl}, "
            + "#{category}, COALESCE(#{useYn},'Y')) "
            + "ON CONFLICT (tenant_id, id) DO UPDATE SET program_name=EXCLUDED.program_name, "
            + "program_type=EXCLUDED.program_type, program_url=EXCLUDED.program_url, "
            + "category=EXCLUDED.category, use_yn=EXCLUDED.use_yn, updated_at=now()")
    int upsert(Map<String, Object> p);

    @Delete("DELETE FROM sys_program WHERE tenant_id = #{tenantId} AND id = #{id}")
    int delete(@Param("tenantId") String tenantId, @Param("id") String id);
}
