package com.ruoyi.system.service.impl;

import com.ruoyi.system.domain.InfoUser;
import com.ruoyi.system.domain.MerchantSubaccountStore;
import com.ruoyi.system.mapper.MerchantSubaccountStoreMapper;
import com.ruoyi.system.service.IMerchantSubaccountStoreService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;

@Service
public class MerchantSubaccountStoreServiceImpl implements IMerchantSubaccountStoreService {

    private final MerchantSubaccountStoreMapper mapper;

    public MerchantSubaccountStoreServiceImpl(MerchantSubaccountStoreMapper mapper) {
        this.mapper = mapper;
    }

    @Override
    public List<Long> selectStoreIdsBySubaccountUserId(Long subaccountUserId) {
        List<Long> storeIds = mapper.selectStoreIdsBySubaccountUserId(subaccountUserId);
        return storeIds == null ? Collections.emptyList() : storeIds;
    }

    @Override
    public List<InfoUser> selectEligibleSubaccountsByStoreId(Long storeId) {
        List<InfoUser> users = mapper.selectEligibleSubaccountsByStoreId(storeId);
        return users == null ? Collections.emptyList() : users;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int replaceRelations(Long subaccountUserId, List<Long> storeIds) {
        int affected = mapper.deleteBySubaccountUserId(subaccountUserId);
        if (storeIds == null || storeIds.isEmpty()) {
            return affected;
        }
        List<MerchantSubaccountStore> relations = storeIds.stream()
                .distinct()
                .map(storeId -> new MerchantSubaccountStore(subaccountUserId, storeId))
                .toList();
        return affected + mapper.insertBatch(relations);
    }

    @Override
    public int deleteByStoreId(Long storeId) {
        return mapper.deleteByStoreId(storeId);
    }

    @Override
    public int insertBatch(List<MerchantSubaccountStore> relations) {
        if (relations == null || relations.isEmpty()) {
            return 0;
        }
        return mapper.insertBatch(relations);
    }
}
