package com.goldenchart.controller;

import com.goldenchart.dto.StrategyDto;
import com.goldenchart.service.StrategyConditionTimeframeService;
import com.goldenchart.service.StrategyService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 투자전략 CRUD REST API.
 *
 * <p>헤더:
 * <ul>
 *   <li>X-Device-Id — 비회원 기기 식별자 (필수)</li>
 *   <li>X-User-Id   — 회원 ID (선택)</li>
 * </ul>
 */
@RestController
@RequestMapping("/strategies")
@RequiredArgsConstructor
public class StrategyController {

    private final StrategyService service;
    private final StrategyConditionTimeframeService conditionTimeframes;

    /** 전략 목록 조회 */
    @GetMapping
    public ResponseEntity<List<StrategyDto>> list(
            @RequestHeader(value = "X-User-Id",   required = false) String userIdHeader,
            @RequestHeader(value = "X-Device-Id", required = false) String deviceId) {
        return ResponseEntity.ok(service.list(parseUserId(userIdHeader), deviceId));
    }

    /** 단일 전략 조회 */
    @GetMapping("/{id}")
    public ResponseEntity<StrategyDto> get(@PathVariable Long id) {
        return service.findById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    /** 전략 저장 (id 없으면 생성, 있으면 수정) */
    @PostMapping
    public ResponseEntity<StrategyDto> save(
            @RequestBody StrategyDto dto,
            @RequestHeader(value = "X-User-Id",   required = false) String userIdHeader,
            @RequestHeader(value = "X-Device-Id", required = false) String deviceId) {
        return ResponseEntity.ok(service.save(dto, parseUserId(userIdHeader), deviceId));
    }

    /** 전략 DSL에 포함된 평가 시간봉 목록 */
    @GetMapping("/{id}/timeframes")
    public ResponseEntity<List<String>> timeframes(@PathVariable Long id) {
        return ResponseEntity.ok(conditionTimeframes.collectForStrategyList(id));
    }

    /** 전략 삭제 */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(@PathVariable Long id) {
        service.delete(id);
        return ResponseEntity.noContent().build();
    }

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