package com.red.circle.other.infra.database.mongo.service.bd;

import com.red.circle.other.infra.database.mongo.entity.bd.BdSalarySettlementRecord;
import com.red.circle.other.infra.enums.BdSettlementStatus;
import com.red.circle.tool.core.date.TimestampUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * BD 结算记录服务实现.
 *
 * @author AI Assistant
 * @since 2025-10-29
 */
@Service
@RequiredArgsConstructor
public class BdSalarySettlementRecordServiceImpl implements BdSalarySettlementRecordService {

    private final MongoTemplate mongoTemplate;

    @Override
    public void create(BdSalarySettlementRecord record) {
        record.setCreateTime(TimestampUtils.now());
        record.setUpdateTime(TimestampUtils.now());
        mongoTemplate.save(record);
    }

    @Override
    public void update(BdSalarySettlementRecord record) {
        record.setUpdateTime(TimestampUtils.now());
        mongoTemplate.save(record);
    }

    @Override
    public BdSalarySettlementRecord getById(String id) {
        return mongoTemplate.findById(id, BdSalarySettlementRecord.class);
    }

    @Override
    public BdSalarySettlementRecord getByBizNo(String bizNo) {
        Query query = new Query(Criteria.where("bizNo").is(bizNo));
        return mongoTemplate.findOne(query, BdSalarySettlementRecord.class);
    }

    @Override
    public boolean existsByBizNo(String bizNo) {
        Query query = new Query(Criteria.where("bizNo").is(bizNo));
        return mongoTemplate.exists(query, BdSalarySettlementRecord.class);
    }

    @Override
    public BdSalarySettlementRecord getByUserIdAndBillBelong(Long bdUserId, Integer billBelong) {
        Query query = new Query(Criteria.where("bdUserId").is(bdUserId)
                .and("billBelong").is(billBelong));
        return mongoTemplate.findOne(query, BdSalarySettlementRecord.class);
    }

    @Override
    public List<BdSalarySettlementRecord> listByBillBelong(Integer billBelong) {
        Query query = new Query(Criteria.where("billBelong").is(billBelong));
        return mongoTemplate.find(query, BdSalarySettlementRecord.class);
    }

    @Override
    public void updateStatus(String id, BdSettlementStatus status, String failureReason) {
        Query query = new Query(Criteria.where("_id").is(id));
        Update update = new Update()
                .set("status", status)
                .set("failureReason", failureReason)
                .set("updateTime", TimestampUtils.now());
        mongoTemplate.updateFirst(query, update, BdSalarySettlementRecord.class);
    }
}
