package com.goldenchart.service;

import com.goldenchart.entity.GcWatchlist;
import com.goldenchart.repository.GcWatchlistRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * 관심종목(DB) 관리 + 실시간 전략 체크 대상 자동 연동.
 *
 * <p>별표로 관심 등록 시 {@code gc_watchlist} 저장과 동시에
 * 해당 종목을 실시간 전략 체크 대상({@code gc_live_strategy_settings})으로 등록한다.
 * 해제 시 전략 체크도 함께 비활성화한다.
 */
@Service
@RequiredArgsConstructor
@Slf4j
@Transactional
public class WatchlistService {

    private final GcWatchlistRepository        watchlistRepo;
    private final LiveStrategySettingsService  liveStrategySettingsService;

    @Transactional(readOnly = true)
    public List<GcWatchlist> list(Long userId, String deviceId) {
        if (userId != null) return watchlistRepo.findByUserIdOrderByDisplayOrderAsc(userId);
        return watchlistRepo.findByDeviceIdOrderByDisplayOrderAsc(deviceId != null ? deviceId : "anonymous");
    }

    public GcWatchlist add(Long userId, String deviceId, String symbol,
                           String koreanName, String englishName, Integer displayOrder) {
        if (symbol == null || symbol.isBlank()) {
            throw new IllegalArgumentException("symbol is required");
        }
        Optional<GcWatchlist> existing = findOne(userId, deviceId, symbol);
        if (existing.isPresent()) {
            liveStrategySettingsService.enableForWatchlistMarket(userId, deviceId, symbol);
            return existing.get();
        }

        int order = displayOrder != null ? displayOrder : nextOrder(userId, deviceId);
        GcWatchlist item = GcWatchlist.builder()
                .userId(userId)
                .deviceId(userId == null ? deviceId : null)
                .symbol(symbol)
                .koreanName(koreanName)
                .englishName(englishName)
                .displayOrder(order)
                .build();
        watchlistRepo.save(item);

        liveStrategySettingsService.enableForWatchlistMarket(userId, deviceId, symbol);
        log.info("[Watchlist] added {} → live strategy enabled", symbol);
        return item;
    }

    public void remove(Long userId, String deviceId, String symbol) {
        if (userId != null) watchlistRepo.deleteByUserIdAndSymbol(userId, symbol);
        else watchlistRepo.deleteByDeviceIdAndSymbol(deviceId != null ? deviceId : "anonymous", symbol);

        liveStrategySettingsService.disableForWatchlistMarket(userId, deviceId, symbol);
        log.info("[Watchlist] removed {} → live strategy disabled", symbol);
    }

    private Optional<GcWatchlist> findOne(Long userId, String deviceId, String symbol) {
        return list(userId, deviceId).stream()
                .filter(w -> symbol.equals(w.getSymbol()))
                .findFirst();
    }

    private int nextOrder(Long userId, String deviceId) {
        List<GcWatchlist> list = list(userId, deviceId);
        return list.isEmpty() ? 0 : list.get(list.size() - 1).getDisplayOrder() + 1;
    }
}
