package study.orderflow.web;

import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.CurrentSecurityContext;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

import jakarta.validation.Valid;

import study.orderflow.service.OrderService;

/// 下单控制器：tenant 只取可信 SecurityContext claim（S02），
/// 请求体里的 tenant 字段一律忽略；scope 与对象归属由注解+服务层共同裁决。
@RestController
public class OrderController {

    private final OrderService service;

    public OrderController(OrderService service) {
        this.service = service;
    }

    @PostMapping("/api/orders")
    @PreAuthorize("hasAuthority('SCOPE_orders.write')")
    public ResponseEntity<OrderResponse> create(
            @CurrentSecurityContext SecurityContext context,
            @RequestHeader(name = "Idempotency-Key", required = false) String idempotencyKey,
            @Valid @RequestBody CreateOrderRequest request) {
        String trustedTenant = context.getAuthentication().getName();
        String key = idempotencyKey == null || idempotencyKey.isBlank()
                ? "auto-" + trustedTenant + "-" + request.sku() + "-" + request.quantity()
                : idempotencyKey;
        return ResponseEntity.ok(service.place(trustedTenant, key, request));
    }

    @GetMapping("/api/orders/{id}")
    @PreAuthorize("hasAuthority('SCOPE_orders.read')")
    public ResponseEntity<OrderResponse> get(
            @CurrentSecurityContext SecurityContext context,
            @PathVariable long id) {
        // 对象归属在服务层以 tenant+id 条件查询；查不到与跨租户呈现同一结果（不泄漏存在性）
        OrderResponse response = service.findOwned(context.getAuthentication().getName(), id);
        return ResponseEntity.ok(response);
    }
}
