package com.lanyuanxiaoyao.bookstore.controller;

import com.lanyuanxiaoyao.bookstore.entity.Book;
import com.lanyuanxiaoyao.bookstore.entity.vo.Option;
import com.lanyuanxiaoyao.bookstore.service.BookService;
import com.lanyuanxiaoyao.service.template.controller.SimpleControllerSupport;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("book")
public class BookController extends SimpleControllerSupport<Book, BookController.SaveItem, BookController.DetailItem, BookController.DetailItem> {
  private final BookService bookService;

  public BookController(BookService service) {
    super(service);
    this.bookService = service;
  }

  @GetMapping("tags")
  public List<Option> tags() {
    return bookService.tags();
  }

  @Override
  protected Function<SaveItem, Book> saveItemMapper() {
    return item -> {
      Book book = new Book();
      book.setId(item.id());
      book.setName(item.name());
      book.setAuthor(item.author());
      book.setDescription(item.description());
      book.setSource(item.source());
      book.setTags(item.tags());
      return book;
    };
  }

  private DetailItem toDetailItem(Book book) {
    return new DetailItem(
        book.getId(),
        book.getName(),
        book.getAuthor(),
        book.getDescription(),
        book.getSource(),
        book.getTags(),
        book.getCreatedTime(),
        book.getModifiedTime()
    );
  }

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

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

  public record SaveItem(
      Long id,
      String name,
      String author,
      String description,
      String source,
      Set<String> tags
  ) {
  }

  public record DetailItem(
      Long id,
      String name,
      String author,
      String description,
      String source,
      Set<String> tags,
      LocalDateTime createdTime,
      LocalDateTime modifiedTime
  ) {
  }
}

