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.BookChaptersEntity;
import com.seer.teach.teacher.module.entity.ReadDurationsEntity;
import com.seer.teach.teacher.service.BookChaptersService;
import com.seer.teach.teacher.service.ReadDurationsService;
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 19:39
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class BookUpdateStudyDurationHandlerImpl implements UpdateLearningDurationHandler {

    private final ReadDurationsService readDurationsService;

    private final BookChaptersService bookChaptersService;

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

    @Override
    public void updateVideoLearningDuration(Integer userId, Integer id, BigDecimal time) {
        BookChaptersEntity chapter = bookChaptersService.getById(id);
        Integer bookId = chapter.getBookId();
        ReadDurationsEntity readDuration = readDurationsService.getOne(new LambdaQueryWrapper<ReadDurationsEntity>()
                .eq(ReadDurationsEntity::getBookId, bookId)
                .eq(ReadDurationsEntity::getChapterId, id)
                .orderByDesc(ReadDurationsEntity::getCreateTime)
                .last("LIMIT 1"));
        readDuration.setEndTime(LocalDateTime.now());
        readDuration.setDurationSeconds((int) Duration.between(readDuration.getStartTime(), readDuration.getEndTime()).getSeconds());
        readDurationsService.updateById(readDuration);
    }

}
