package com.pandoli365.bibimbap.mapper;

import com.pandoli365.bibimbap.data.TagData;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

@Mapper
public interface TagsMapper {

    @Insert("""
            INSERT INTO tags (
                name,
                slug,
                tag_type,
                is_active,
                created_by
            ) VALUES (
                #{name},
                #{slug},
                #{tagType},
                #{isActive},
                #{createdBy}
            )
            """)
    @Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
    int insertTag(TagData t);

    @Update("UPDATE tags SET is_active = TRUE WHERE id = #{id}")
    void approve(long id);

    @Update("UPDATE tags SET is_active = FALSE WHERE id = #{id}")
    void deactivate(long id);

    @Select("""
            <script>
            SELECT
                id,
                name,
                slug,
                tag_type AS tagType,
                is_active AS isActive,
                created_by AS createdBy,
                created_at AS createdAt
            FROM tags
            WHERE is_active = TRUE
            <if test="tagType != null"> AND tag_type = #{tagType} </if>
            <if test="q != null and q != ''"> AND (name ILIKE ('%' || #{q} || '%') OR slug ILIKE ('%' || #{q} || '%')) </if>
            ORDER BY name ASC, id ASC
            </script>
            """)
    List<TagData> listActiveByType(@Param("tagType") String tagType, @Param("q") String q);

    @Select("""
            SELECT
                id,
                name,
                slug,
                tag_type AS tagType,
                is_active AS isActive,
                created_by AS createdBy,
                created_at AS createdAt
            FROM tags
            WHERE slug = #{slug}
            """)
    TagData findBySlug(String slug);
}
