package com.starry.admin.modules.withdraw.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.starry.admin.modules.withdraw.entity.ClerkPayeeProfileEntity;
import com.starry.admin.modules.withdraw.mapper.ClerkPayeeProfileMapper;
import com.starry.admin.modules.withdraw.service.IClerkPayeeProfileService;
import com.starry.common.utils.IdUtils;
import java.time.LocalDateTime;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class ClerkPayeeProfileServiceImpl extends ServiceImpl<ClerkPayeeProfileMapper, ClerkPayeeProfileEntity>
        implements IClerkPayeeProfileService {

    private static final String DEFAULT_CHANNEL = "ALIPAY_QR";

    @Override
    public ClerkPayeeProfileEntity getByClerk(String tenantId, String clerkId) {
        return lambdaQuery()
                .eq(ClerkPayeeProfileEntity::getTenantId, tenantId)
                .eq(ClerkPayeeProfileEntity::getClerkId, clerkId)
                .last("limit 1")
                .one();
    }

    @Override
    public ClerkPayeeProfileEntity upsertProfile(String tenantId, String clerkId, String channel,
                                                 String qrCodeUrl, String displayName, String operator) {
        String resolvedChannel = StringUtils.hasText(channel) ? channel : DEFAULT_CHANNEL;
        ClerkPayeeProfileEntity profile = getByClerk(tenantId, clerkId);
        if (profile == null) {
            profile = new ClerkPayeeProfileEntity();
            profile.setId(IdUtils.getUuid());
            profile.setTenantId(tenantId);
            profile.setClerkId(clerkId);
        }
        profile.setChannel(resolvedChannel);
        profile.setQrCodeUrl(qrCodeUrl);
        profile.setDisplayName(displayName);
        profile.setLastConfirmedAt(null); // force confirmation before next withdrawal
        profile.setUpdatedBy(operator);
        if (profile.getCreatedBy() == null) {
            profile.setCreatedBy(operator);
        }
        this.saveOrUpdate(profile);
        return profile;
    }

    @Override
    public ClerkPayeeProfileEntity confirmProfile(String tenantId, String clerkId, String operator) {
        ClerkPayeeProfileEntity profile = getByClerk(tenantId, clerkId);
        if (profile == null) {
            return null;
        }
        profile.setLastConfirmedAt(LocalDateTime.now());
        profile.setUpdatedBy(operator);
        updateById(profile);
        return profile;
    }
}
