package com.ffii.fhsmsc.modules.food_nutrients.service;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ffii.core.exception.InternalServerErrorException;
import com.ffii.core.support.AbstractBaseEntityService;
import com.ffii.core.support.JdbcDao;
import com.ffii.core.utils.BeanUtils;
import com.ffii.fhsmsc.modules.food_nutrients.entity.food_nutrients;
import com.ffii.fhsmsc.modules.food_nutrients.entity.food_nutrientsRepository;
import com.ffii.fhsmsc.modules.food_nutrients.req.food_nutrientsReq;

import jakarta.validation.Valid;

@Service
public class food_nutrientsService extends AbstractBaseEntityService<food_nutrients, Long, food_nutrientsRepository>{
    private static final Logger logger = LoggerFactory.getLogger(food_nutrientsService.class);
    
    public food_nutrientsService(JdbcDao jdbcDao, food_nutrientsRepository repository) {
		super(jdbcDao, repository);
	}

    public List<Map<String, Object>> search(Map<String, Object> args) {
        logger.info("Search called with args: {}", args);
        StringBuilder sql = new StringBuilder();
        
        // Check if we need to fetch records for embedding processing
        if (args != null && args.containsKey("embedding_text")) {
            sql.append("SELECT pi.id, pi.embedding_text");
        } else if (args != null && args.containsKey("embedding_vector")) {
            sql.append("SELECT pi.id, pi.embedding_vector");
        } else {
            // Normal case - return all fields except embeddings
            sql.append("SELECT"
                + " pi.id,"
                + " pi.food_name,"
                + " pi.brand,"
                + " pi.size_kg,"
                + " pi.protein_percent,"
                + " pi.fat_percent,"
                + " pi.fibre_percent,"
                + " pi.ash_percent,"
                + " pi.taurine_percent,"
                + " pi.vitamin_a_iu_kg,"
                + " pi.vitamin_d_iu_kg,"
                + " pi.vitamin_e_mg_kg,"
                + " pi.phosphorus_percent,"
                + " pi.calcium_percent,"
                + " pi.magnesium_percent,"
                + " pi.methionine_percent,"
                + " pi.moisture_percent,"
                + " pi.omega_3_mg_kg,"
                + " pi.omega_6_mg_kg,"
                + " pi.vitamin_c_mg_kg,"
                + " pi.calories_kcal_kg,"
                + " pi.food_type,"
                + " pi.target_age_category,"
                + " pi.pet,"
                + " pi.description");
        }
        
        sql.append(" FROM food_nutrients pi")
           .append(" WHERE pi.deleted = 0");  // 使用 0，因为是 tinyint(1)
    
        if (args != null) {
            if (args.containsKey("food_name")) {
                sql.append(" AND pi.food_name = :food_name");
                logger.info("Added food_name filter: {}", args.get("food_name"));
            }
            if (args.containsKey("id")) {
                sql.append(" AND pi.id = :id");
                logger.info("Added id filter: {}", args.get("id"));
            }
        }
    
        sql.append(" ORDER BY pi.id");
        logger.info("Final SQL query: {}", sql.toString());
        
        List<Map<String, Object>> result = jdbcDao.queryForList(sql.toString(), args);
        logger.info("Query returned {} results", result.size());
        return result;
    }

    @Transactional(rollbackFor = Exception.class)
	public food_nutrients saveOrUpdate(@Valid food_nutrientsReq req) {
		food_nutrients instance;

		if (req.getId() != null && req.getId() > 0) {
			// 更新现有记录
			instance = find(req.getId()).orElseThrow(InternalServerErrorException::new);
			
			// 只更新非空字段
			if (req.getFood_name() != null) {
				instance.setFood_name(req.getFood_name());
			}
			if (req.getBrand() != null) {
				instance.setBrand(req.getBrand());
			}
			if (req.getSize_kg() != null) {
				instance.setSize_kg(req.getSize_kg());
			}
			if (req.getProtein_percent() != null) {
				instance.setProtein_percent(req.getProtein_percent());
			}
			if (req.getFat_percent() != null) {
				instance.setFat_percent(req.getFat_percent());
			}
			if (req.getFibre_percent() != null) {
				instance.setFibre_percent(req.getFibre_percent());
			}
			if (req.getAsh_percent() != null) {
				instance.setAsh_percent(req.getAsh_percent());
			}
			if (req.getTaurine_percent() != null) {
				instance.setTaurine_percent(req.getTaurine_percent());
			}
			if (req.getVitamin_a_iu_kg() != null) {
				instance.setVitamin_a_iu_kg(req.getVitamin_a_iu_kg());
			}
			if (req.getVitamin_d_iu_kg() != null) {
				instance.setVitamin_d_iu_kg(req.getVitamin_d_iu_kg());
			}
			if (req.getVitamin_e_mg_kg() != null) {
				instance.setVitamin_e_mg_kg(req.getVitamin_e_mg_kg());
			}
			if (req.getPhosphorus_percent() != null) {
				instance.setPhosphorus_percent(req.getPhosphorus_percent());
			}
			if (req.getCalcium_percent() != null) {
				instance.setCalcium_percent(req.getCalcium_percent());
			}
			if (req.getMagnesium_percent() != null) {
				instance.setMagnesium_percent(req.getMagnesium_percent());
			}
			if (req.getMethionine_percent() != null) {
				instance.setMethionine_percent(req.getMethionine_percent());
			}
			if (req.getMoisture_percent() != null) {
				instance.setMoisture_percent(req.getMoisture_percent());
			}
			if (req.getOmega_3_mg_kg() != null) {
				instance.setOmega_3_mg_kg(req.getOmega_3_mg_kg());
			}
			if (req.getOmega_6_mg_kg() != null) {
				instance.setOmega_6_mg_kg(req.getOmega_6_mg_kg());
			}
			if (req.getVitamin_c_mg_kg() != null) {
				instance.setVitamin_c_mg_kg(req.getVitamin_c_mg_kg());
			}
			if (req.getCalories_kcal_kg() != null) {
				instance.setCalories_kcal_kg(req.getCalories_kcal_kg());
			}
			if (req.getFood_type() != null) {
				instance.setFood_type(req.getFood_type());
			}
			if (req.getTarget_age_category() != null) {
				instance.setTarget_age_category(req.getTarget_age_category());
			}
			if (req.getPet() != null) {
				instance.setPet(req.getPet());
			}
			if (req.getEmbedding_text() != null) {
				instance.setEmbedding_text(req.getEmbedding_text());
			}
			if (req.getEmbedding_vector() != null) {
				instance.setEmbedding_vector(req.getEmbedding_vector());
			}
			if (req.getDescription() != null) {
				instance.setDescription(req.getDescription());
			}
		} else {
			// 创建新记录
			instance = new food_nutrients();
			BeanUtils.copyProperties(req, instance);
		}
	
		saveAndFlush(instance);
		return instance;
	}
}
