package com.goldenchart.controller;

import com.goldenchart.dto.PaperOrderRequest;
import com.goldenchart.dto.PaperSummaryDto;
import com.goldenchart.dto.PaperTradeDto;
import com.goldenchart.service.PaperTradingService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

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

@RestController
@RequestMapping("/paper")
@RequiredArgsConstructor
public class PaperTradingController {

    private final PaperTradingService paperTradingService;

    private Long userId(Map<String, String> h) {
        String v = h.get("x-user-id");
        return v != null ? Long.parseLong(v) : null;
    }

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

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

    @PostMapping("/summary")
    public ResponseEntity<PaperSummaryDto> summaryWithMarks(
            @RequestHeader Map<String, String> h,
            @RequestBody(required = false) Map<String, Double> markPrices) {
        return ResponseEntity.ok(paperTradingService.getSummary(userId(h), deviceId(h), markPrices));
    }

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

    @PostMapping("/orders")
    public ResponseEntity<PaperTradeDto> placeOrder(
            @RequestHeader Map<String, String> h,
            @RequestBody PaperOrderRequest body) {
        return ResponseEntity.ok(paperTradingService.placeOrder(userId(h), deviceId(h), body));
    }

    @PostMapping("/reset")
    public ResponseEntity<PaperSummaryDto> reset(@RequestHeader Map<String, String> h) {
        return ResponseEntity.ok(paperTradingService.resetAccount(userId(h), deviceId(h)));
    }
}
