package com.erp.platformsync.controller;

import com.erp.common.core.model.ApiResponse;
import com.erp.platformsync.dto.PlatformSyncRequest;
import com.erp.platformsync.dto.PullOrdersResponse;
import com.erp.platformsync.service.PlatformSyncService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 平台同步控制器
 * 提供订单同步到平台和从平台拉取订单的API
 * 对应Feign客户端: com.erp.order.client.PlatformSyncClient
 */
@Slf4j
@RestController
@RequestMapping("/api/platform")
@RequiredArgsConstructor
public class PlatformSyncController {

    private final PlatformSyncService platformSyncService;

    /**
     * 同步订单状态到平台
     * POST /api/platform/sync/order
     */
    @PostMapping("/sync/order")
    public ApiResponse<?> syncOrderToPlatform(@RequestBody PlatformSyncRequest request) {
        try {
            PlatformSyncService.SyncResult result = platformSyncService.syncOrderToPlatform(request);
            if (result.success()) {
                return ApiResponse.success(result.message());
            } else {
                return ApiResponse.error(400, result.message());
            }
        } catch (Exception e) {
            log.error("同步订单到平台异常: {}", e.getMessage(), e);
            return ApiResponse.error(500, "同步失败: " + e.getMessage());
        }
    }

    /**
     * 从平台拉取订单
     * GET /api/platform/pull/orders
     */
    @GetMapping("/pull/orders")
    public ApiResponse<List<PullOrdersResponse.PullOrderItem>> pullOrdersFromPlatform(
            @RequestParam String platform,
            @RequestParam Long shopId,
            @RequestParam String pullType,
            @RequestParam(required = false) String orderIds,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime) {
        try {
            List<PullOrdersResponse.PullOrderItem> orders = platformSyncService.pullOrdersFromPlatform(
                    platform, shopId, pullType, orderIds, startTime, endTime);
            PullOrdersResponse response = PullOrdersResponse.builder()
                    .total(orders.size())
                    .orders(orders)
                    .build();
            return ApiResponse.success(response);
        } catch (Exception e) {
            log.error("从平台拉取订单异常: {}", e.getMessage(), e);
            return ApiResponse.error(500, "拉取失败: " + e.getMessage());
        }
    }
}
