package com.lanyuanxiaoyao.bookstore.service;

import cn.hutool.core.util.NumberUtil;
import com.lanyuanxiaoyao.bookstore.entity.Chapter;
import com.lanyuanxiaoyao.bookstore.entity.QChapter;
import com.lanyuanxiaoyao.bookstore.entity.vo.Option;
import com.lanyuanxiaoyao.bookstore.repository.ChapterRepository;
import com.lanyuanxiaoyao.service.template.service.SimpleServiceSupport;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class ChapterService extends SimpleServiceSupport<Chapter> {
  private final ChapterRepository chapterRepository;

  public ChapterService(ChapterRepository repository) {
    super(repository);
    this.chapterRepository = repository;
  }

  public List<Option> chapters() {
    return list()
        .stream()
        .map(chapter -> new Option(chapter.getName(), chapter.getId()))
        .toList();
  }

  public Double latestSequence(Long bookId) {
    return chapterRepository.findMaxSequence(bookId).orElse(0.0);
  }

  public void generateSequence() {
    var chapters = chapterRepository.findAll(QChapter.chapter.sequence.asc());
    for (int index = 0; index < chapters.size(); index++) {
      chapters.get(index).setSequence(NumberUtil.toDouble(index));
    }
    chapterRepository.saveAll(chapters);
  }
}

