package com.example.orders;

import java.util.Iterator;

/**
 * 注文金額の計算。割引・税・送料のルールが歴史的経緯で積み重なっている。
 */
public class PriceCalculator {

    private ProductRepository productRepository;

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

    // memberRank: GOLD / SILVER / NONE, couponCode: WELCOME ほか(nullあり)
    public int calcTotal(Order order, String memberRank, String couponCode) {
        int subtotal = 0;
        int totalQuantity = 0;
        Iterator it = order.getLines().iterator();
        while (it.hasNext()) {
            OrderLine line = (OrderLine) it.next();
            Product p = productRepository.findById(line.getProductId());
            if (p == null) {
                throw new IllegalArgumentException("unknown product: " + line.getProductId());
            }
            int linePrice = p.getPrice() * line.getQuantity();
            // 書籍は軽減税率
            if (p.getCategory().equals("BOOK")) {
                linePrice = (int) (linePrice * 1.08);
            } else {
                linePrice = (int) (linePrice * 1.10);
            }
            subtotal = subtotal + linePrice;
            totalQuantity = totalQuantity + line.getQuantity();
        }

        // 会員ランク割引
        if (memberRank != null) {
            if (memberRank.equals("GOLD")) {
                subtotal = (int) (subtotal * 0.95);
            } else if (memberRank.equals("SILVER")) {
                subtotal = (int) (subtotal * 0.97);
            }
        }

        // まとめ買い割引(10個以上で2%)
        if (totalQuantity >= 10) {
            subtotal = (int) (subtotal * 0.98);
        }

        // クーポン(税・割引適用後の金額が3000円以上のとき500円引き)
        if (couponCode != null && couponCode.equals("WELCOME")) {
            if (subtotal >= 3000) {
                subtotal = subtotal - 500;
            }
        }

        // 送料(割引後5000円未満は600円。5000円ちょうどは無料)
        if (subtotal < 5000) {
            subtotal = subtotal + 600;
        }

        return subtotal;
    }
}
