package com.goldenchart.controller;

import com.goldenchart.dto.LiveStrategyBulkRequest;
import com.goldenchart.dto.LiveStrategySettingsDto;
import com.goldenchart.service.LiveStrategySettingsService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 실시간 전략 체크 설정 REST API.
 *
 * <pre>
 * GET  /api/strategy/settings?market=KRW-BTC   → 현재 설정 조회
 * PUT  /api/strategy/settings                  → 설정 저장/갱신
 * </pre>
 */
@RestController
@RequestMapping("/strategy/settings")
@RequiredArgsConstructor
public class LiveStrategySettingsController {

    private final LiveStrategySettingsService service;

    @GetMapping
    public ResponseEntity<LiveStrategySettingsDto> get(
            @RequestParam(value = "market", defaultValue = "KRW-BTC") String market,
            @RequestHeader(value = "X-User-Id",   required = false) String userIdHeader,
            @RequestHeader(value = "X-Device-Id", required = false) String deviceId) {

        return ResponseEntity.ok(service.get(parseUserId(userIdHeader), deviceId, market));
    }

    @PutMapping
    public ResponseEntity<LiveStrategySettingsDto> put(
            @RequestBody LiveStrategySettingsDto dto,
            @RequestHeader(value = "X-User-Id",   required = false) String userIdHeader,
            @RequestHeader(value = "X-Device-Id", required = false) String deviceId) {

        return ResponseEntity.ok(service.save(parseUserId(userIdHeader), deviceId, dto));
    }

    /** 실시간 체크 ON + 전략 지정된 종목 목록 (현재 디바이스/유저) */
    @GetMapping("/active")
    public ResponseEntity<List<LiveStrategySettingsDto>> listActive(
            @RequestHeader(value = "X-User-Id",   required = false) String userIdHeader,
            @RequestHeader(value = "X-Device-Id", required = false) String deviceId) {

        return ResponseEntity.ok(service.listActive(parseUserId(userIdHeader), deviceId));
    }

    /** 관심종목 등 여러 마켓에 동일 설정 일괄 저장 */
    @PutMapping("/bulk")
    public ResponseEntity<List<LiveStrategySettingsDto>> putBulk(
            @RequestBody LiveStrategyBulkRequest req,
            @RequestHeader(value = "X-User-Id",   required = false) String userIdHeader,
            @RequestHeader(value = "X-Device-Id", required = false) String deviceId) {

        return ResponseEntity.ok(service.saveBulk(parseUserId(userIdHeader), deviceId, req));
    }

    private Long parseUserId(String header) {
        if (header == null || header.isBlank()) return null;
        try { return Long.parseLong(header); } catch (NumberFormatException e) { return null; }
    }
}
