package com.lanyuanxiaoyao.bookstore.controller;

import com.lanyuanxiaoyao.bookstore.entity.Line;
import com.lanyuanxiaoyao.bookstore.service.LineService;
import com.lanyuanxiaoyao.service.template.controller.GlobalResponse;
import com.lanyuanxiaoyao.service.template.controller.SimpleControllerSupport;
import java.util.function.Function;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("line")
public class LineController extends SimpleControllerSupport<Line, LineController.SaveItem, LineController.DetailItem, LineController.DetailItem> {
  private final LineService lineService;

  public LineController(LineService service) {
    super(service);
    this.lineService = service;
  }

  @PostMapping("load")
  public GlobalResponse<Object> load(@RequestBody LineController.LoadItem item) {
    lineService.load(item.chapterId(), item.content());
    return GlobalResponse.responseSuccess();
  }

  @GetMapping("generate_sequence/{chapter_id}")
  public GlobalResponse<Object> generateSequence(@PathVariable("chapter_id") Long chapterId) {
    lineService.generateSequence(chapterId);
    return GlobalResponse.responseSuccess();
  }

  @Override
  protected Function<SaveItem, Line> saveItemMapper() {
    return item -> {
      var line = lineService.detailOrThrow(item.id());
      line.setText(item.text());
      return line;
    };
  }

  private DetailItem toDetailItem(Line line) {
    return new DetailItem(
        line.getId(),
        line.getSequence(),
        line.getText()
    );
  }

  @Override
  protected Function<Line, DetailItem> listItemMapper() {
    return this::toDetailItem;
  }

  @Override
  protected Function<Line, DetailItem> detailItemMapper() {
    return this::toDetailItem;
  }

  public record SaveItem(
      Long id,
      Long chapterId,
      String text
  ) {
  }

  public record LoadItem(
      Long chapterId,
      String content
  ) {
  }

  public record DetailItem(
      Long id,
      Double sequence,
      String text
  ) {
  }
}

