package com.example.scaffold.controller;

import com.example.scaffold.dto.OrderCreateRequest;
import com.example.scaffold.dto.ProductCreateRequest;
import com.example.scaffold.entity.Order;
import com.example.scaffold.entity.Product;
import com.example.scaffold.mapper.ProductMapper;
import com.example.scaffold.service.impl.OrderService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 产品和订单控制器 - 演示事务
 */
@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
public class ProductOrderController {
    
    private final ProductMapper productMapper;
    private final OrderService orderService;
    
    // ==================== 产品 API ====================
    
    @GetMapping("/products")
    public List<Product> listProducts() {
        return productMapper.findAll();
    }
    
    @GetMapping("/products/{id}")
    public ResponseEntity<Product> getProduct(@PathVariable Long id) {
        Product product = productMapper.findById(id);
        return product != null ? ResponseEntity.ok(product) : ResponseEntity.notFound().build();
    }
    
    @GetMapping("/products/category/{category}")
    public List<Product> getByCategory(@PathVariable String category) {
        return productMapper.findByCategory(category);
    }
    
    @GetMapping("/products/price")
    public List<Product> getByPriceRange(@RequestParam BigDecimal min, @RequestParam BigDecimal max) {
        return productMapper.findByPriceRange(min, max);
    }
    
    @PostMapping("/products")
    public ResponseEntity<Product> createProduct(@Valid @RequestBody ProductCreateRequest request) {
        Product product = new Product();
        product.setName(request.getName());
        product.setDescription(request.getDescription());
        product.setPrice(request.getPrice());
        product.setStockQuantity(request.getStockQuantity());
        product.setCategory(request.getCategory());
        
        productMapper.insert(product);
        return ResponseEntity.ok(product);
    }
    
    @DeleteMapping("/products/{id}")
    public ResponseEntity<Void> deleteProduct(@PathVariable Long id) {
        productMapper.deleteById(id);
        return ResponseEntity.noContent().build();
    }
    
    // ==================== 订单 API ====================
    
    @GetMapping("/orders")
    public List<Order> listOrders() {
        return orderService.findAll();
    }
    
    @GetMapping("/orders/{id}")
    public ResponseEntity<Order> getOrder(@PathVariable Long id) {
        Order order = orderService.getOrder(id);
        return order != null ? ResponseEntity.ok(order) : ResponseEntity.notFound().build();
    }
    
    @GetMapping("/orders/user/{userId}")
    public List<Order> getOrdersByUser(@PathVariable Long userId) {
        return orderService.findByUserId(userId);
    }
    
    /**
     * 创建订单 - 演示事务
     */
    @PostMapping("/orders")
    public ResponseEntity<?> createOrder(@Valid @RequestBody OrderCreateRequest request) {
        try {
            Order order = orderService.createOrderWithRollback(
                    request.getUserId(),
                    request.getProductId(),
                    request.getQuantity(),
                    request.isRollback()
            );
            return ResponseEntity.ok(Map.of(
                    "success", true,
                    "order", order,
                    "message", request.isRollback() ? "事务已回滚，但订单仍创建（REQUIRES_NEW演示）" : "订单创建成功"
            ));
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(Map.of(
                    "success", false,
                    "error", e.getMessage()
            ));
        }
    }
    
    @PatchMapping("/orders/{id}/status")
    public ResponseEntity<Void> updateOrderStatus(@PathVariable Long id, @RequestParam String status) {
        orderService.updateStatus(id, status);
        return ResponseEntity.ok().build();
    }
    
    @DeleteMapping("/orders/{id}")
    public ResponseEntity<Void> deleteOrder(@PathVariable Long id) {
        orderService.deleteById(id);
        return ResponseEntity.noContent().build();
    }
}