package com.yaoai.admin.plan;

import com.yaoai.admin.auth.StpAdminUtil;
import com.yaoai.admin.plan.dto.PlanUpdateRequest;
import com.yaoai.common.exception.BizException;
import com.yaoai.common.exception.ErrorCode;
import com.yaoai.domain.entity.Plan;
import com.yaoai.domain.mapper.PlanMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
public class PlanAdminService {

    private final PlanMapper planMapper;

    public List<Plan> list() {
        return planMapper.selectList(com.baomidou.mybatisplus.core.toolkit.Wrappers.<Plan>lambdaQuery()
                .orderByAsc(Plan::getId));
    }

    @Transactional
    public Plan update(Long id, PlanUpdateRequest request) {
        Plan plan = planMapper.selectById(id);
        if (plan == null) {
            throw new BizException(ErrorCode.NOT_FOUND, "套餐不存在");
        }
        if (request.getName() != null) plan.setName(request.getName());
        if (request.getPriceMonthly() != null) plan.setPriceMonthly(request.getPriceMonthly());
        if (request.getMonthlyCredits() != null) plan.setMonthlyCredits(request.getMonthlyCredits());
        if (request.getMaxMembers() != null) plan.setMaxMembers(request.getMaxMembers());
        if (request.getMaxProjects() != null) plan.setMaxProjects(request.getMaxProjects());
        if (request.getMaxConcurrentTasks() != null) plan.setMaxConcurrentTasks(request.getMaxConcurrentTasks());
        if (request.getFeatures() != null) plan.setFeatures(request.getFeatures());
        if (request.getIsActive() != null) plan.setIsActive(request.getIsActive());
        plan.setUpdatedAt(LocalDateTime.now());
        plan.setUpdatedBy(StpAdminUtil.getLoginIdAsLong());
        planMapper.updateById(plan);
        return planMapper.selectById(id);
    }
}
