package com.example.demo.service;

import com.example.demo.model.SyncRecord;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 接口集成服务。
 * <p>提供标准化RESTful API，支持第三方系统数据对接与同步，记录同步日志。</p>
 */
@Service
public class IntegrationService {

    private final Map<Long, SyncRecord> syncRecordMap = new ConcurrentHashMap<>();
    private final AtomicLong syncIdCounter = new AtomicLong(1);

    public IntegrationService() {
        syncRecordMap.put(syncIdCounter.getAndIncrement(),
                new SyncRecord(1L, "外部系统A", "本系统", "full",
                        "2026-01-10 02:00:00", "success", 150, null));
        syncRecordMap.put(syncIdCounter.getAndIncrement(),
                new SyncRecord(2L, "本系统", "外部系统B", "incremental",
                        "2026-01-11 03:00:00", "success", 20, null));
    }

    /**
     * API认证（模拟）。
     *
     * @requirement(name="预留标准化接口", id="SRS-F-06-001")
     * 提供标准化RESTful API接口，支持认证鉴权。
     */
    public Map<String, Object> auth(String apiKey, String secret) {
        Map<String, Object> result = new LinkedHashMap<>();
        if ("demo-key".equals(apiKey) && "demo-secret".equals(secret)) {
            result.put("token", "Bearer " + UUID.randomUUID().toString().replace("-", ""));
            result.put("expiresIn", 3600);
        } else {
            result.put("error", "认证失败");
            result.put("code", 401);
        }
        return result;
    }

    /**
     * 数据推送。
     *
     * @requirement(name="支持与第三方系统数据对接、数据同步", id="SRS-F-06-002")
     * 第三方系统推送数据到本系统。
     */
    public Map<String, Object> pushData(List<Map<String, Object>> dataList, String syncType) {
        long id = syncIdCounter.getAndIncrement();
        SyncRecord record = new SyncRecord(id, "外部系统", "本系统",
                syncType != null ? syncType : "realTime",
                java.time.LocalDateTime.now().toString().replace("T", " "),
                "success", dataList != null ? dataList.size() : 0, null);
        syncRecordMap.put(id, record);
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("syncId", id);
        result.put("status", "success");
        result.put("receivedCount", dataList != null ? dataList.size() : 0);
        return result;
    }

    /**
     * 数据拉取。
     *
     * @requirement(name="支持与第三方系统数据对接、数据同步", id="SRS-F-06-002")
     * 本系统从第三方系统拉取数据。
     */
    public Map<String, Object> pullData(String sourceSystem, String syncType) {
        long id = syncIdCounter.getAndIncrement();
        SyncRecord record = new SyncRecord(id, sourceSystem, "本系统",
                syncType != null ? syncType : "timed",
                java.time.LocalDateTime.now().toString().replace("T", " "),
                "success", 10, null);
        syncRecordMap.put(id, record);
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("syncId", id);
        result.put("status", "success");
        result.put("sourceSystem", sourceSystem);
        result.put("dataCount", 10);
        return result;
    }

    /**
     * 查询同步状态。
     *
     * @requirement(name="支持与第三方系统数据对接、数据同步", id="SRS-F-06-002")
     * 查询数据同步记录的状态。
     */
    public List<SyncRecord> listSyncRecords(String sourceSystem, String status) {
        List<SyncRecord> all = new ArrayList<>(syncRecordMap.values());
        if (sourceSystem != null && !sourceSystem.isEmpty()) {
            all = all.stream().filter(r -> sourceSystem.equals(r.getSourceSystem())).toList();
        }
        if (status != null && !status.isEmpty()) {
            all = all.stream().filter(r -> status.equals(r.getStatus())).toList();
        }
        return all;
    }
}
