package com.utopiaindustries.restcontroller;

import com.utopiaindustries.dao.uind.ItemDAO;
import com.utopiaindustries.model.uind.Item;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping( "/rest/items" )
public class ItemRestController {

    private final ItemDAO itemDAO;

    public ItemRestController(ItemDAO itemDAO) {
        this.itemDAO = itemDAO;
    }

    @GetMapping("/search")
    public List<Item> searchItemByTitle(@RequestParam String term,
                                        @RequestParam(name = "type-ids", required = false) Long[] typeIds ) {

        List<Item> items;
        // if type ids are present, search them
        if (typeIds != null && typeIds.length > 0) {
            items = itemDAO.findBySkuOrTitleAndTypeIdAndActive(term, Arrays.stream(typeIds).collect(Collectors.toList()), "1" );
        } else {
            // else return all results
            items = itemDAO.findLikeTitleAndStatus(term, true );
        }
        return items;
    }
}
