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

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.seer.teach.common.enums.ResultCodeEnum;
import com.seer.teach.common.enums.UserRelationEnum;
import com.seer.teach.common.utils.AssertUtils;
import com.seer.teach.user.entity.UserFamilyEntity;
import com.seer.teach.user.entity.UserRelationEntity;
import com.seer.teach.user.mapper.UserFamilyMapper;
import com.seer.teach.user.service.IUserFamilyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seer.teach.user.service.IUserRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * <p>
 * 我的家庭 服务实现类
 * </p>
 *
 * @author ZS
 * @since 2025-09-19
 */
@Service
public class UserFamilyServiceImpl extends ServiceImpl<UserFamilyMapper, UserFamilyEntity> implements IUserFamilyService {

    @Autowired
    private IUserRelationService userRelationService;

    @Override
    public Optional<UserFamilyEntity> getUserFamilyByChildId(Integer childId) {
        Integer parentId = userRelationService.getParentIdByChildrenId(childId);
        if(Objects.nonNull(parentId)){
            return Optional.of(super.getOne(new LambdaQueryWrapper<>(UserFamilyEntity.class).eq(UserFamilyEntity::getPrimaryGuardianUserId, childId)));
        }
        return Optional.empty();
    }

    @Override
    public Optional<UserFamilyEntity> getUserFamilyByGuardianUserId(Integer guardianUserId) {
        List<UserRelationEntity> userRelations = userRelationService.getUserRelationByUserIdAndType(guardianUserId, UserRelationEnum.PARENT_CHILD);
        if(CollectionUtil.isEmpty(userRelations)){
            return Optional.empty();
        }
        Optional<Integer> first = userRelations.stream().map(UserRelationEntity::getFamilyId).findFirst();
        if(first.isPresent()){
            return Optional.of(super.getOne(new LambdaQueryWrapper<>(UserFamilyEntity.class).eq(UserFamilyEntity::getPrimaryGuardianUserId, guardianUserId)));
        }
        return Optional.empty();
    }

    @Override
    public Optional<List<UserRelationEntity>> checkUserFamily(Integer userId, Integer familyId) {
        List<UserRelationEntity> userRelations = userRelationService.getUserRelationByUserIdAndFamilyId(userId, familyId);
        AssertUtils.notEmpty(userRelations, ResultCodeEnum.USER_FAMILY_NOT_EXIST);
        return Optional.of(userRelations);
    }
}
