package com.example.orders;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

public class OrderValidator {

    private ProductRepository productRepository;

    public OrderValidator(ProductRepository productRepository) {
        this.productRepository = productRepository;
    }

    public List<String> validate(Order order) {
        List<String> errors = new ArrayList<String>();
        if (order == null) {
            errors.add("order is null");
            return errors;
        }
        if (order.getCustomerId() == null || order.getCustomerId().trim().length() == 0) {
            errors.add("customerId is required");
        }
        if (order.getLines() == null || order.getLines().size() == 0) {
            errors.add("order must have at least 1 line");
            return errors;
        }
        Set<String> seen = new HashSet<String>();
        Iterator it = order.getLines().iterator();
        while (it.hasNext()) {
            OrderLine line = (OrderLine) it.next();
            if (line.getQuantity() <= 0) {
                errors.add("quantity must be positive: " + line.getProductId());
            }
            if (line.getQuantity() > 99) {
                errors.add("quantity too large (max 99): " + line.getProductId());
            }
            Product p = productRepository.findById(line.getProductId());
            if (p == null) {
                errors.add("unknown product: " + line.getProductId());
            } else {
                if (p.getStock() < line.getQuantity()) {
                    errors.add("out of stock: " + line.getProductId());
                }
            }
            if (seen.contains(line.getProductId())) {
                errors.add("duplicated line: " + line.getProductId());
            }
            seen.add(line.getProductId());
        }
        return errors;
    }
}
