package com.ffii.fhsmsc.modules.diet_records.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.diet_records.entity.diet_records;
import com.ffii.fhsmsc.modules.diet_records.entity.diet_recordsRepository;
import com.ffii.fhsmsc.modules.diet_records.req.diet_recordsReq;

import jakarta.validation.Valid;

@Service
public class diet_recordsService extends AbstractBaseEntityService<diet_records, Long, diet_recordsRepository>{
    private static final Logger logger = LoggerFactory.getLogger(diet_recordsService.class);
    
    public diet_recordsService(JdbcDao jdbcDao, diet_recordsRepository 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("SELECT"
				+ " dr.id,"
				+ " dr.food_id,"
				+ " dr.date,"
				+ " dr.meal_type,"
				+ " dr.size,"
				+ " dr.user_id"
				+ " FROM diet_records dr"
				+ " WHERE dr.deleted = 0"  // 使用 0，因为是 tinyint(1)
				);
		if (args != null) {
			if (args.containsKey("user_id")) {
				sql.append(" AND dr.user_id = :user_id");
				logger.info("Added user_id filter: {}", args.get("user_id"));
			}
			// Add date range filters
			if (args.containsKey("start_date")) {
				sql.append(" AND dr.date >= :start_date");
				logger.info("Added start_date filter: {}", args.get("start_date"));
			}
			if (args.containsKey("end_date")) {
				sql.append(" AND dr.date <= :end_date");
				logger.info("Added end_date filter: {}", args.get("end_date"));
			}
		}

		sql.append(" ORDER BY dr.date, dr.meal_type");  // Changed ordering to make more sense
		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 diet_records saveOrUpdate(@Valid diet_recordsReq req) {
		diet_records instance;

		if (req.getId() != null && req.getId() > 0) {
			// 更新现有记录
			instance = find(req.getId()).orElseThrow(InternalServerErrorException::new);
			
			// 只更新非空字段
			if (req.getFood_id() != null) {
				instance.setFood_id(req.getFood_id());
			}
			if (req.getDate() != null) {
				instance.setDate(req.getDate());
			}
			if (req.getMeal_type() != null) {
				instance.setMeal_type(req.getMeal_type());
			}
			if (req.getSize() != null) {
				instance.setSize(req.getSize());
			}
			if (req.getUser_id() != null) {
				instance.setUser_id(req.getUser_id());
			}

		} else {
			// 创建新记录
			instance = new diet_records();
			BeanUtils.copyProperties(req, instance);
		}
	
		saveAndFlush(instance);
		return instance;
	}
}
