package com.lesingle.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lesingle.edu.common.enums.ErrorCode;
import com.lesingle.edu.common.exception.BusinessException;
import com.lesingle.edu.entity.ParentStudent;
import com.lesingle.edu.entity.TaskCompletion;
import com.lesingle.edu.mapper.ParentStudentMapper;
import com.lesingle.edu.mapper.TaskCompletionMapper;
import com.lesingle.edu.service.ParentAuthService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * 家长端鉴权服务实现
 */
@Service
@RequiredArgsConstructor
public class ParentAuthServiceImpl implements ParentAuthService {

    private final ParentStudentMapper parentStudentMapper;
    private final TaskCompletionMapper taskCompletionMapper;

    @Override
    public void validateParentStudentRelation(Long parentId, Long studentId) {
        if (parentId == null || studentId == null) {
            throw new BusinessException(ErrorCode.INVALID_PARAMETER, "家长ID或学生ID不能为空");
        }
        Long count = parentStudentMapper.selectCount(
                new LambdaQueryWrapper<ParentStudent>()
                        .eq(ParentStudent::getParentId, parentId)
                        .eq(ParentStudent::getStudentId, studentId)
        );
        if (count == null || count == 0) {
            throw new BusinessException(ErrorCode.PERMISSION_DENIED, "无权访问该学生的数据");
        }
    }

    @Override
    public void validateParentCanAccessCompletion(Long parentId, Long completionId) {
        TaskCompletion completion = taskCompletionMapper.selectById(completionId);
        if (completion == null) {
            throw new BusinessException(ErrorCode.DATA_NOT_FOUND, "完成记录不存在");
        }
        validateParentStudentRelation(parentId, completion.getStudentId());
    }
}
