package com.nanri.aiimage.modules.shopkey.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.modules.shopkey.mapper.ShopKeyMapper;
import com.nanri.aiimage.modules.shopkey.model.dto.ShopKeyCreateRequest;
import com.nanri.aiimage.modules.shopkey.model.dto.ShopKeyUpdateRequest;
import com.nanri.aiimage.modules.shopkey.model.entity.ShopKeyEntity;
import com.nanri.aiimage.modules.shopkey.model.vo.ShopKeyItemVo;
import com.nanri.aiimage.modules.shopkey.model.vo.ShopKeyPageVo;
import com.nanri.aiimage.modules.ziniao.service.ZiniaoShopIndexService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
@Slf4j
public class ShopKeyService {

    private final ShopKeyMapper shopKeyMapper;
    private final ZiniaoShopIndexService ziniaoShopIndexService;

    public ShopKeyPageVo page(long page, long pageSize) {
        long safePage = Math.max(page, 1);
        long safePageSize = Math.min(Math.max(pageSize, 1), 100);
        LambdaQueryWrapper<ShopKeyEntity> query = new LambdaQueryWrapper<ShopKeyEntity>()
                .orderByDesc(ShopKeyEntity::getId);
        Long total = shopKeyMapper.selectCount(query);
        List<ShopKeyItemVo> items = shopKeyMapper.selectList(query.last("LIMIT " + ((safePage - 1) * safePageSize) + ", " + safePageSize))
                .stream()
                .map(this::toItemVo)
                .toList();
        ShopKeyPageVo vo = new ShopKeyPageVo();
        vo.setItems(items);
        vo.setTotal(total);
        vo.setPage(safePage);
        vo.setPageSize(safePageSize);
        return vo;
    }

    @Transactional
    public ShopKeyItemVo create(ShopKeyCreateRequest request) {
        String ziniaoAccountName = normalizeRequired(request.getZiniaoAccountName(), "紫鸟账号名称不能为空");
        String ziniaoToken = normalizeRequired(request.getZiniaoToken(), "紫鸟令牌不能为空");
        ShopKeyEntity entity = new ShopKeyEntity();
        entity.setZiniaoAccountName(ziniaoAccountName);
        entity.setZiniaoToken(ziniaoToken);
        shopKeyMapper.insert(entity);
        triggerShopIndexRefresh();
        return toItemVo(getById(entity.getId()));
    }

    @Transactional
    public ShopKeyItemVo update(Long id, ShopKeyUpdateRequest request) {
        ShopKeyEntity entity = getById(id);
        String ziniaoAccountName = normalizeRequired(request.getZiniaoAccountName(), "紫鸟账号名称不能为空");
        String ziniaoToken = normalizeRequired(request.getZiniaoToken(), "紫鸟令牌不能为空");
        entity.setZiniaoAccountName(ziniaoAccountName);
        entity.setZiniaoToken(ziniaoToken);
        shopKeyMapper.updateById(entity);
        triggerShopIndexRefresh();
        return toItemVo(getById(id));
    }

    @Transactional
    public void delete(Long id) {
        ShopKeyEntity entity = getById(id);
        shopKeyMapper.deleteById(entity.getId());
        triggerShopIndexRefresh();
    }

    private ShopKeyEntity getById(Long id) {
        ShopKeyEntity entity = shopKeyMapper.selectById(id);
        if (entity == null) {
            throw new BusinessException("店铺密钥不存在");
        }
        return entity;
    }

    private String normalizeRequired(String value, String message) {
        String normalized = value == null ? "" : value.trim();
        if (normalized.isEmpty()) {
            throw new BusinessException(message);
        }
        return normalized;
    }

    private ShopKeyItemVo toItemVo(ShopKeyEntity entity) {
        ShopKeyItemVo vo = new ShopKeyItemVo();
        vo.setId(entity.getId());
        vo.setZiniaoAccountName(entity.getZiniaoAccountName());
        vo.setZiniaoToken(entity.getZiniaoToken());
        vo.setCreatedAt(entity.getCreatedAt());
        vo.setUpdatedAt(entity.getUpdatedAt());
        return vo;
    }

    private void triggerShopIndexRefresh() {
        try {
            ziniaoShopIndexService.invalidateIndex();
        } catch (Exception ex) {
            log.warn("[ziniao-index] refresh trigger failed after shop key change: {}", ex.getMessage());
        }
    }
}
