package com.lanyuanxiaoyao.leopard.server.controller;

import com.lanyuanxiaoyao.leopard.core.entity.StockCollection;
import com.lanyuanxiaoyao.leopard.core.service.StockCollectionService;
import com.lanyuanxiaoyao.leopard.server.entity.StockScoreVo;
import com.lanyuanxiaoyao.service.template.controller.GlobalResponse;
import com.lanyuanxiaoyao.service.template.controller.SimpleControllerSupport;
import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;
import java.util.function.Function;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("stock_collection")
public class StockCollectionController extends SimpleControllerSupport<StockCollection, Void, StockCollectionController.ListItem, StockCollectionController.DetailItem> {
  public StockCollectionController(StockCollectionService service) {
    super(service);
  }

  @Override
  public GlobalResponse<Long> save(Void unused) throws Exception {
    throw new UnsupportedOperationException();
  }

  @Override
  protected Function<Void, StockCollection> saveItemMapper() {
    throw new UnsupportedOperationException();
  }

  @Override
  protected Function<StockCollection, ListItem> listItemMapper() {
    return collection -> new ListItem(
      collection.getId(),
      collection.getName(),
      collection.getDescription(),
      collection.getScores().size(),
      collection.getCreatedTime(),
      collection.getModifiedTime()
    );
  }

  @Override
  protected Function<StockCollection, DetailItem> detailItemMapper() {
    return collection -> new DetailItem(
      collection.getId(),
      collection.getName(),
      collection.getDescription(),
      collection.getScores().size(),
      collection.getScores()
        .stream()
        .map(StockScoreVo::of)
        .sorted(Comparator.comparing(StockScoreVo::score).reversed())
        .toList(),
      collection.getCreatedTime(),
      collection.getModifiedTime()
    );
  }

  public record ListItem(
    Long id,
    String name,
    String description,
    Integer count,
    LocalDateTime createdTime,
    LocalDateTime modifiedTime
  ) {
  }

  public record DetailItem(
    Long id,
    String name,
    String description,
    Integer count,
    List<StockScoreVo> scores,
    LocalDateTime createdTime,
    LocalDateTime modifiedTime
  ) {
  }
}
