package com.example.demo.controller;

import com.example.demo.model.ApiResult;
import com.example.demo.model.SyncRecord;
import com.example.demo.service.IntegrationService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 接口集成控制器。
 * <p>提供标准化RESTful API，支持第三方系统认证、数据推送、数据拉取及同步状态查询。</p>
 */
@RestController
@RequestMapping("/api/v1")
@Tag(name = "接口集成", description = "接口集成模块接口（需求标识：SRS-F-06-001~SRS-F-06-002）")
public class IntegrationController {

    private final IntegrationService integrationService;

    public IntegrationController(IntegrationService integrationService) {
        this.integrationService = integrationService;
    }

    /**
     * API认证。
     *
     * @requirement(name="预留标准化接口", id="SRS-F-06-001")
     */
    @PostMapping("/auth")
    @Operation(summary = "API认证", description = "第三方系统调用接口前的认证鉴权")
    public ApiResult<Map<String, Object>> auth(@RequestParam String apiKey, @RequestParam String secret) {
        Map<String, Object> result = integrationService.auth(apiKey, secret);
        if (result.containsKey("error")) {
            return ApiResult.error(401, (String) result.get("error"));
        }
        return ApiResult.success(result);
    }

    /**
     * 数据推送。
     *
     * @requirement(name="支持与第三方系统数据对接、数据同步", id="SRS-F-06-002")
     */
    @PostMapping("/push")
    @Operation(summary = "数据推送", description = "第三方系统推送数据到本系统")
    public ApiResult<Map<String, Object>> push(@RequestBody List<Map<String, Object>> dataList,
                                                @RequestParam(required = false) String syncType) {
        return ApiResult.success(integrationService.pushData(dataList, syncType));
    }

    /**
     * 数据拉取。
     *
     * @requirement(name="支持与第三方系统数据对接、数据同步", id="SRS-F-06-002")
     */
    @GetMapping("/pull")
    @Operation(summary = "数据拉取", description = "本系统从第三方系统拉取数据")
    public ApiResult<Map<String, Object>> pull(@RequestParam String sourceSystem,
                                                @RequestParam(required = false) String syncType) {
        return ApiResult.success(integrationService.pullData(sourceSystem, syncType));
    }

    /**
     * 同步状态查询。
     *
     * @requirement(name="支持与第三方系统数据对接、数据同步", id="SRS-F-06-002")
     */
    @GetMapping("/sync/status")
    @Operation(summary = "同步状态查询", description = "查询数据同步记录的状态")
    public ApiResult<List<SyncRecord>> syncStatus(@RequestParam(required = false) String sourceSystem,
                                                   @RequestParam(required = false) String status) {
        return ApiResult.success(integrationService.listSyncRecords(sourceSystem, status));
    }
}
