package com.jeesharp.business.modules.food.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jeesharp.business.modules.food.entity.FoodCompany;
import com.jeesharp.business.modules.food.mapper.FoodCompanyMapper;
import com.jeesharp.business.modules.food.service.FoodCompanyService;
import com.jeesharp.framework.mybatis.core.service.CrudService;
import com.jeesharp.framework.pojo.query.PaginationVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(readOnly = true)
public class FoodCompanyServiceImpl extends CrudService<FoodCompanyMapper, FoodCompany, PaginationVO> implements FoodCompanyService {

    private static final String DEL_NORMAL = "0";
    private static final int STATUS_ENABLED = 1;
    private static final int DEFAULT_LIMIT = 20;
    private static final int MAX_LIMIT = 50;

    @Override
    public FoodCompany getById(String companyId) {
        return getBaseMapper().selectById(companyId);
    }

    @Override
    public FoodCompany getEnabledCompany(String companyId) {
        if (StrUtil.isBlank(companyId)) {
            return null;
        }
        return getBaseMapper().selectOne(new LambdaQueryWrapper<FoodCompany>()
            .eq(FoodCompany::getId, companyId)
            .eq(FoodCompany::getStatus, STATUS_ENABLED)
            .eq(FoodCompany::getDelFlag, DEL_NORMAL)
            .last("limit 1"));
    }

    @Override
    public List<FoodCompany> searchEnabledCompanies(String keyword, int limit) {
        int safeLimit = limit <= 0 ? DEFAULT_LIMIT : Math.min(limit, MAX_LIMIT);
        LambdaQueryWrapper<FoodCompany> wrapper = new LambdaQueryWrapper<FoodCompany>()
            .eq(FoodCompany::getStatus, STATUS_ENABLED)
            .eq(FoodCompany::getDelFlag, DEL_NORMAL)
            .orderByAsc(FoodCompany::getCompanyName)
            .last("limit " + safeLimit);
        if (StrUtil.isNotBlank(keyword)) {
            String value = keyword.trim();
            wrapper.and(w -> w.like(FoodCompany::getCompanyName, value).or().like(FoodCompany::getCompanyCode, value));
        }
        return getBaseMapper().selectList(wrapper);
    }
}
