package com.ga.api.service.product;

import com.ga.common.exception.BizException;
import com.ga.common.exception.ErrorCode;
import com.ga.common.model.PageResponse;
import com.ga.core.mapper.product.ProductMapper;
import com.ga.core.vo.product.ProductResp;
import com.ga.core.vo.product.ProductVO;
import com.github.pagehelper.PageHelper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
public class ProductService {

    private final ProductMapper mapper;

    @Transactional(readOnly = true)
    public PageResponse<ProductResp> list(int pageNum, int pageSize, Long companyId, String insuranceType, String keyword, String isActive) {
        PageHelper.startPage(pageNum, pageSize);
        return PageResponse.of(mapper.selectList(companyId, insuranceType, keyword, isActive));
    }

    @Transactional(readOnly = true)
    public ProductResp detail(Long productId) {
        ProductResp r = mapper.selectDetailById(productId);
        if (r == null) throw new BizException(ErrorCode.NOT_FOUND);
        return r;
    }

    @Transactional
    public Long create(ProductVO vo) {
        if (mapper.existsByCode(vo.getCompanyId(), vo.getProductCode()) > 0) {
            throw new BizException(ErrorCode.DUPLICATE_DATA);
        }
        mapper.insert(vo);
        return vo.getProductId();
    }

    @Transactional
    public void update(Long productId, ProductVO vo) {
        if (mapper.selectById(productId) == null) throw new BizException(ErrorCode.NOT_FOUND);
        vo.setProductId(productId);
        mapper.update(vo);
    }

    @Transactional
    public void delete(Long productId) {
        if (mapper.selectById(productId) == null) throw new BizException(ErrorCode.NOT_FOUND);
        mapper.deleteById(productId);
    }
}
