package com.zioinfo.mall.product;

import com.zioinfo.mall.product.mapper.ProductMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class ProductService {

    private final ProductMapper mapper;

    public Map<String, Object> search(Long categoryId, String keyword, String status,
                                      String occasion, String flowerType, java.math.BigDecimal maxPrice,
                                      String sort, int page, int size) {
        int safeSize = (size <= 0 || size > 100) ? 20 : size;
        int safePage = Math.max(page, 0);
        List<MallProduct> items = mapper.search(categoryId, keyword, status, occasion, flowerType, maxPrice,
                sort, safeSize, safePage * safeSize);
        int total = mapper.countSearch(categoryId, keyword, status, occasion, flowerType, maxPrice);
        Map<String, Object> out = new LinkedHashMap<>();
        out.put("items", items);
        out.put("total", total);
        out.put("page", safePage);
        out.put("size", safeSize);
        return out;
    }

    /** 상세 — 옵션·이미지 포함. */
    public MallProduct detail(Long id) {
        MallProduct p = mapper.findById(id);
        if (p == null) {
            throw new RuntimeException("ERR-PRD-404: 상품을 찾을 수 없습니다");
        }
        p.setOptions(mapper.findOptions(id));
        p.setImages(mapper.findImages(id));
        p.setSizes(mapper.findSizes(id));
        return p;
    }

    @Transactional
    public MallProduct create(MallProduct p) {
        if (p.getName() == null || p.getName().isBlank()) {
            throw new IllegalArgumentException("ERR-PRD-400: 상품명 필수");
        }
        if (p.getPrice() == null) {
            throw new IllegalArgumentException("ERR-PRD-400: 가격 필수");
        }
        mapper.insert(p);
        persistChildren(p);
        return detail(p.getId());
    }

    @Transactional
    public MallProduct update(Long id, MallProduct p) {
        p.setId(id);
        mapper.update(p);
        if (p.getOptions() != null) {
            mapper.deleteOptions(id);
        }
        if (p.getImages() != null) {
            mapper.deleteImages(id);
        }
        if (p.getSizes() != null) {
            mapper.deleteSizes(id);
        }
        persistChildren(p);
        return detail(id);
    }

    private void persistChildren(MallProduct p) {
        if (p.getOptions() != null) {
            for (MallProductOption o : p.getOptions()) {
                o.setProductId(p.getId());
                mapper.insertOption(o);
            }
        }
        if (p.getImages() != null) {
            for (MallProductImage img : p.getImages()) {
                img.setProductId(p.getId());
                mapper.insertImage(img);
            }
        }
        if (p.getSizes() != null) {
            for (MallProductSize s : p.getSizes()) {
                s.setProductId(p.getId());
                mapper.insertSize(s);
            }
        }
    }

    public void updateStatus(Long id, String status) {
        mapper.updateStatus(id, status);
    }

    public void delete(Long id) {
        mapper.deleteOptions(id);
        mapper.deleteImages(id);
        mapper.delete(id);
    }
}
