package com.seer.teach.teacher.service.registry.updateLearningDuration.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.seer.teach.common.enums.teacher.ModuleEnum;
import com.seer.teach.teacher.module.entity.TreasuryArticleReadDurationsEntity;
import com.seer.teach.teacher.service.TreasuryArticleReadDurationsService;
import com.seer.teach.teacher.service.registry.updateLearningDuration.UpdateLearningDurationHandler;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;

/**
 *
 * <p>
 *
 * </p >
 *
 * @author Captain
 * @since 2025-09-20 20:38
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TreasureChestsReadingUpdateLearningDurationHandlerImpl implements UpdateLearningDurationHandler {

    private final TreasuryArticleReadDurationsService treasuryArticleReadDurationsService;

    @Override
    public Integer getType() {
        return ModuleEnum.TREASURE_CHESTS_READING.getCode();
    }

    @Override
    public void updateVideoLearningDuration(Integer userId, Integer id, BigDecimal time) {
        TreasuryArticleReadDurationsEntity readDuration = treasuryArticleReadDurationsService.getOne(new LambdaQueryWrapper<TreasuryArticleReadDurationsEntity>()
                .eq(TreasuryArticleReadDurationsEntity::getArticleId, id)
                .eq(TreasuryArticleReadDurationsEntity::getUserId, userId)
                .orderByDesc(TreasuryArticleReadDurationsEntity::getCreateTime)
                .last("LIMIT 1"));
        readDuration.setEndTime(LocalDateTime.now());
        readDuration.setDurationSeconds((int) Duration.between(readDuration.getStartTime(), readDuration.getEndTime()).getSeconds());
        treasuryArticleReadDurationsService.updateById(readDuration);
    }
}
