package com.goldenchart.controller;

import com.goldenchart.dto.LiveOrderRequest;
import com.goldenchart.dto.LiveOrderRequest;
import com.goldenchart.dto.LiveSummaryDto;
import com.goldenchart.dto.LiveTradeDto;
import com.goldenchart.service.LiveTradingService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/live")
@RequiredArgsConstructor
public class LiveTradingController {

    private final LiveTradingService liveTradingService;

    @GetMapping("/summary")
    public ResponseEntity<LiveSummaryDto> summary(@RequestHeader Map<String, String> h) {
        return ResponseEntity.ok(liveTradingService.getSummary(userId(h), deviceId(h)));
    }

    @GetMapping("/trades")
    public ResponseEntity<List<LiveTradeDto>> trades(@RequestHeader Map<String, String> h) {
        return ResponseEntity.ok(liveTradingService.listTrades(userId(h), deviceId(h)));
    }

    @PostMapping("/orders")
    public ResponseEntity<LiveTradeDto> placeOrder(@RequestHeader Map<String, String> h,
                                                   @RequestBody LiveOrderRequest body) {
        return ResponseEntity.ok(liveTradingService.placeManualOrder(userId(h), deviceId(h), body));
    }

    private Long userId(Map<String, String> h) {
        String v = h.get("x-user-id");
        if (v == null || v.isBlank()) return null;
        try { return Long.parseLong(v); } catch (NumberFormatException e) { return null; }
    }

    private String deviceId(Map<String, String> h) {
        return h.getOrDefault("x-device-id", "anonymous");
    }
}
