package com.pandoli365.bibimbap.mapper;

import com.pandoli365.bibimbap.data.PostCategoryData;
import org.apache.ibatis.annotations.Delete;
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 PostCategoriesMapper {

    @Select("""
            SELECT
                id,
                name,
                slug,
                sort_order AS sortOrder,
                is_active AS isActive,
                created_at AS createdAt,
                updated_at AS updatedAt
            FROM post_categories
            WHERE is_active = true
            ORDER BY sort_order ASC, id ASC
            """)
    List<PostCategoryData> listActive();

    @Select("""
            SELECT
                id,
                name,
                slug,
                sort_order AS sortOrder,
                is_active AS isActive,
                created_at AS createdAt,
                updated_at AS updatedAt
            FROM post_categories
            WHERE id = #{id}
              AND is_active = true
            """)
    PostCategoryData getActive(@Param("id") long id);

    @Select("""
            SELECT
                id,
                name,
                slug,
                sort_order AS sortOrder,
                is_active AS isActive,
                created_at AS createdAt,
                updated_at AS updatedAt
            FROM post_categories
            WHERE id = #{id}
            """)
    PostCategoryData getById(@Param("id") long id);

    @Insert("""
            INSERT INTO post_categories (
                name,
                slug,
                sort_order
            ) VALUES (
                #{name},
                #{slug},
                #{sortOrder}
            )
            """)
    @Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
    int insert(PostCategoryData c);

    @Update("""
            UPDATE post_categories
            SET name = #{name},
                slug = #{slug},
                sort_order = #{sortOrder},
                is_active = #{isActive},
                updated_at = now()
            WHERE id = #{id}
            """)
    int update(PostCategoryData c);

    @Delete("""
            DELETE FROM post_categories
            WHERE id = #{id}
            """)
    int delete(@Param("id") long id);

    @Select("""
            SELECT count(*)
            FROM posts
            WHERE category_id = #{categoryId}
              AND is_delete = false
              AND status = 'PUBLISHED'
            """)
    int countPostsByCategory(@Param("categoryId") long categoryId);
}
