package com.microservices.zone.member.service.points.handler;

import com.microservices.zone.member.domain.points.ZonePointsAccount;
import com.microservices.zone.member.mapper.ZonePointsAccountMapper;
import com.microservices.zone.member.mapper.ZonePointsTransactionMapper;
import com.microservices.zone.member.service.points.IPointsTaskHandler;
import com.microservices.zone.member.service.points.PointsAccountOperations;
import com.microservices.zone.member.service.points.PointsTaskContext;
import com.microservices.zone.utils.ZoneConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * 发布项目审核通过 — 积分奖励
 *
 * @author otto
 */
@Component
public class PublishProjectPointsHandler implements IPointsTaskHandler {

    @Autowired
    private PointsAccountOperations pointsAccountOperations;

    @Autowired
    private ZonePointsAccountMapper zonePointsAccountMapper;

    @Autowired
    private ZonePointsTransactionMapper zonePointsTransactionMapper;

    private static final Logger logger = LoggerFactory.getLogger(PublishProjectPointsHandler.class);

    @Override
    public String getSourceType() {
        return ZoneConstants.PublishProject.SOURCE_TYPE;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handle(PointsTaskContext ctx) {
        pointsAccountOperations.resolveZoneId(ctx);

        ZonePointsAccount account = pointsAccountOperations.getOrCreateAccount(ctx.getUserId(), ctx.getZoneId());
        if (account == null) {
            return;
        }

        // 幂等检查：同一来源同一用户只发放一次
        if (zonePointsTransactionMapper.countByEventTypeAndSourceAndUser(ZoneConstants.PublishProject.SOURCE_TYPE, ctx.getSourceId(), account.getId()) > 0) {
            logger.info("积分-项目发布：积分已发放，跳过 sourceId={} userId={}", ctx.getSourceId(), ctx.getUserId());
            return;
        }

        ZonePointsAccount locked = zonePointsAccountMapper.selectZonePointsAccountByIdForUpdate(account.getId());
        int availableAfter = locked.getAvailablePoints() + ZoneConstants.PublishProject.POINTS;
        int frozenAfter = locked.getFrozenPoints();

        zonePointsAccountMapper.addPointsAtomic(account.getId(), ZoneConstants.PublishProject.POINTS);

        pointsAccountOperations.recordPointsTransaction(account.getId(),
                ZoneConstants.TransactionType.ADD,
                ZoneConstants.PublishProject.POINTS,
                availableAfter, frozenAfter,
                ZoneConstants.PublishProject.REASON, ctx.getOperatorId(), ctx.getSourceId(),
                ZoneConstants.PublishProject.SOURCE_TYPE, null,
                ZoneConstants.PublishProject.SUBJECT,
                String.format(ZoneConstants.PublishProject.SUBJECT_DESC_TEMPLATE, ctx.getSubjectDesc()),
                null);
    }
}