package com.lanyuanxiaoyao.leopard.server.controller;

import com.lanyuanxiaoyao.leopard.core.entity.Stock;
import com.lanyuanxiaoyao.leopard.core.entity.StockCollection;
import com.lanyuanxiaoyao.leopard.server.service.StockCollectionService;
import com.lanyuanxiaoyao.leopard.server.service.StockService;
import com.lanyuanxiaoyao.service.template.controller.SimpleControllerSupport;
import java.util.HashSet;
import java.util.Set;
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, StockCollectionController.SaveItem, StockCollectionController.ListItem, StockCollectionController.DetailItem> {
  private final StockService stockService;

  public StockCollectionController(StockCollectionService service, StockService stockService) {
    super(service);
    this.stockService = stockService;
  }

  @Override
  protected Function<SaveItem, StockCollection> saveItemMapper() {
    return item -> {
      var collection = new StockCollection();
      collection.setId(item.id());
      collection.setName(item.name());
      collection.setDescription(item.description());
      var stocks = stockService.list(item.stockIds());
      collection.setStocks(new HashSet<>(stocks));
      return collection;
    };
  }

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

  @Override
  protected Function<StockCollection, DetailItem> detailItemMapper() {
    return collection -> new DetailItem(
      collection.getId(),
      collection.getName(),
      collection.getDescription(),
      collection.getStocks().size(),
      collection.getStocks()
    );
  }

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

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

  public record DetailItem(
    Long id,
    String name,
    String description,
    Integer count,
    Set<Stock> stocks
  ) {
  }
}
