package com.usky.issue.service.support;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.usky.common.security.utils.SecurityUtils;
import com.usky.issue.domain.CloudAuditEntity;
import com.usky.issue.domain.IssueCloudConfig;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.time.LocalDateTime;

/**
 * 实体审计字段填充
 *
 * @author fyc
 * @date 2026-05-21
 */
public final class CloudEntitySupport {

    private CloudEntitySupport() {
    }

    public static String resolveOperator() {
        String username = SecurityUtils.getUsername();
        return StringUtils.isBlank(username) ? "system" : username;
    }

    public static String resolveRequestIp() {
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attrs == null) {
            return null;
        }
        return attrs.getRequest().getRemoteAddr();
    }

    /**
     * 解析当前请求的访问令牌，用于转发至云端 HTTP 调用（Authorization: Bearer）
     */
    public static String resolveAccessToken() {
        String fromHeader = resolveAuthorizationHeader();
        if (StringUtils.isNotBlank(fromHeader)) {
            return stripBearerPrefix(fromHeader);
        }
        try {
            String fromSecurity = SecurityUtils.getToken();
            if (StringUtils.isNotBlank(fromSecurity)) {
                return stripBearerPrefix(fromSecurity);
            }
        } catch (Exception ignored) {
            // 非 Web 上下文或无登录态
        }
        return null;
    }

    public static String resolveAccessToken(IssueCloudConfig config) {
        if (config != null && StringUtils.isNotBlank(config.getToken())) {
            return stripBearerPrefix(config.getToken());
        }
        return resolveAccessToken();
    }

    private static String resolveAuthorizationHeader() {
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attrs == null) {
            return null;
        }
        return attrs.getRequest().getHeader("Authorization");
    }

    private static String stripBearerPrefix(String token) {
        if (token == null) {
            return null;
        }
        String trimmed = token.trim();
        if (trimmed.regionMatches(true, 0, "Bearer ", 0, 7)) {
            return trimmed.substring(7).trim();
        }
        return trimmed;
    }

    public static void fillOnInsert(CloudAuditEntity entity) {
        LocalDateTime now = LocalDateTime.now();
        if (entity.getTenantId() == null) {
            entity.setTenantId(SecurityUtils.getTenantId());
        }
        entity.setCreatedBy(resolveOperator());
        entity.setCreatedTime(now);
        entity.setUpdatedTime(now);
        if (entity.getIsDeleted() == null) {
            entity.setIsDeleted(0);
        }
    }

    public static void fillOnUpdate(CloudAuditEntity entity) {
        entity.setUpdatedTime(LocalDateTime.now());
        entity.setUpdatedBy(resolveOperator());
    }
}
