package com.goldenchart.trading;

import com.goldenchart.entity.GcAppSettings;
import com.goldenchart.service.AppSettingsService;
import com.goldenchart.service.LiveTradingService;
import com.goldenchart.service.PaperTradingService;
import com.goldenchart.trading.pipeline.OrderRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 운영 모드(PAPER / LIVE / BOTH)에 따라 모의·실거래 실행을 분기한다.
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class TradingExecutionService {

    private final AppSettingsService appSettingsService;
    private final PaperTradingService paperTradingService;
    private final LiveTradingService liveTradingService;

    public void executeSignal(String deviceId, Long userId, String market,
                              Long strategyId, String side, double price) {
        GcAppSettings app = appSettingsService.getEntity(userId, deviceId);
        TradingMode mode = TradingMode.fromString(app.getTradingMode());

        if (mode.usePaper() && Boolean.TRUE.equals(app.getPaperTradingEnabled())) {
            paperTradingService.tryExecuteOnSignal(deviceId, userId, market, strategyId, side, price);
        }
        if (mode.useLive()) {
            liveTradingService.tryExecuteOnSignal(
                    deviceId, userId, market, strategyId, side, price, "STRATEGY");
        }
    }

    public void executeRiskExit(OrderRequest req) {
        GcAppSettings app = appSettingsService.getEntity(req.userId(), req.deviceId());
        TradingMode mode = TradingMode.fromString(app.getTradingMode());
        String source = req.kind() == OrderRequest.OrderKind.STOP_LOSS ? "STOP_LOSS" : "TAKE_PROFIT";

        if (mode.usePaper() && Boolean.TRUE.equals(app.getPaperTradingEnabled())) {
            paperTradingService.tryExecuteOnSignal(
                    req.deviceId(), req.userId(), req.market(), null, "SELL", req.price());
        }
        if (mode.useLive()) {
            liveTradingService.tryExecuteOnSignal(
                    req.deviceId(), req.userId(), req.market(), null, "SELL", req.price(), source);
        }
    }
}
