package com.alterdekim.game.repository;

import com.alterdekim.game.component.game.avatar.BodyPartType;
import com.alterdekim.game.component.game.inventory.InventoryItem;
import com.alterdekim.game.entity.BodyPart;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
public interface BodyPartRepository extends JpaRepository<BodyPart, Long> {
    Optional<BodyPart> findById(Long id);

    @Query(value = "SELECT b FROM BodyPart b WHERE b.type = :type")
    List<BodyPart> findByBodyPartType(@Param("type") BodyPartType type);

    @Query(value = """
                    SELECT 
                        a.id AS id, 
                        0 AS textResourceId, 
                        a.id AS bodyPartId, 
                        a.media_resource_id AS mediaResourceId, 
                        (case when (MAX(a.is_used) > 0) then 1 else 0 end) AS isUsed, 
                        (case when (a.is_colorable > 0) then 1 else 0 end) AS isColorable, 
                        MAX(a.color) AS color, 
                        0 AS isLimited, 
                        '' AS date, 
                        0 AS pollution, 
                        1 AS isBodyPart, 
                        0 AS phoneId 
                    FROM (
                        SELECT 
                            b.id, 
                            b.is_colorable, 
                            b.media_resource_id, 
                            b.`type`, 
                            0 AS is_used, 
                            0 AS color 
                        FROM bodyparts AS b 
                        UNION (
                            SELECT 
                                b.id, 
                                b.is_colorable, 
                                b.media_resource_id, 
                                b.`type`, 
                                a.is_used, 
                                a.color 
                            FROM bodyparts AS b 
                                JOIN avatar_inventory AS a 
                            ON b.id = a.good_id 
                            WHERE a.`type` = 'BodyParts' AND a.user_id = :uid
                            )
                        ) AS a 
                    WHERE a.`type` = :#{#type.name()} 
                    GROUP BY a.id, a.`type`, a.media_resource_id, a.is_colorable""", nativeQuery = true)
    List<InventoryItem> findInventoryItems(@Param("uid") Integer userId, @Param("type") BodyPartType type);
}