package com.seer.teach.mp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seer.teach.common.constants.CommonConstant;
import com.seer.teach.mp.entity.MpActivityFormRelationEntity;
import com.seer.teach.mp.mapper.MpActivityFormRelationMapper;
import com.seer.teach.mp.service.IMpActivityFormRelationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * <p>
 * 活动与表单模板关联表 服务实现类
 * </p>
 *
 * @author Lingma
 * @since 2026-01-10
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class MpActivityFormRelationServiceImpl extends ServiceImpl<MpActivityFormRelationMapper, MpActivityFormRelationEntity> implements IMpActivityFormRelationService {

    @Override
    public Integer getPrimaryFormIdByActivityId(Integer activityId) {
        MpActivityFormRelationEntity relation = this.getOne(
            new LambdaQueryWrapper<MpActivityFormRelationEntity>()
                .eq(MpActivityFormRelationEntity::getActivityId, activityId)
                    .eq(MpActivityFormRelationEntity::getIsPrimary, CommonConstant.ENABLE)
        );
        return relation != null ? relation.getFormId() : null;
    }

    @Override
    public long getCountByActivityId(Integer activityId) {
        return super.count(new LambdaQueryWrapper<MpActivityFormRelationEntity>().eq(MpActivityFormRelationEntity::getActivityId, activityId));
    }

    @Override
    public boolean createRelation(Integer activityId, Integer formId) {
        // 检查是否已经存在关联
        MpActivityFormRelationEntity existing = this.getOne(
            new LambdaQueryWrapper<MpActivityFormRelationEntity>()
                .eq(MpActivityFormRelationEntity::getActivityId, activityId)
                .eq(MpActivityFormRelationEntity::getFormId, formId)
        );
        
        if (existing != null) {
            return this.updateById(existing);
        } else {
            // 创建新的关联
            MpActivityFormRelationEntity relation = new MpActivityFormRelationEntity();
            relation.setActivityId(activityId);
            relation.setFormId(formId);

            return this.save(relation);
        }
    }

    @Override
    public Optional<MpActivityFormRelationEntity> getLatestVersionByActivityId(Integer activityId) {
        MpActivityFormRelationEntity relation = this.getOne(
            new LambdaQueryWrapper<MpActivityFormRelationEntity>()
                .eq(MpActivityFormRelationEntity::getActivityId, activityId)
                .orderByDesc(MpActivityFormRelationEntity::getId)
                .last("LIMIT 1")
        );
        log.info("getLatestVersionByActivityId: {}", relation);
        return Optional.ofNullable(relation);
    }
}