using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using SIGCM.Application.DTOs; using SIGCM.Application.Interfaces; using SIGCM.Domain.Interfaces; // Para acceder a repos de lectura directa si hace falta namespace SIGCM.API.Controllers; [ApiController] [Route("api/[controller]")] [Authorize] public class OrdersController : ControllerBase { private readonly IOrderService _orderService; private readonly IOrderRepository _orderRepo; // Para lecturas simples (GET) public OrdersController(IOrderService orderService, IOrderRepository orderRepo) { _orderService = orderService; _orderRepo = orderRepo; } // Crear una nueva orden de venta [HttpPost] public async Task Create(CreateOrderDto dto) { try { // Seguridad: Forzar que el vendedor sea el usuario logueado si no se especifica var userIdClaim = User.FindFirst("Id")?.Value; if (int.TryParse(userIdClaim, out int userId)) { dto.SellerId = userId; } var result = await _orderService.CreateOrderAsync(dto); return Ok(result); } catch (Exception ex) { return BadRequest(new { message = ex.Message }); } } // Obtener historial de órdenes de un cliente [HttpGet("client/{clientId}")] public async Task GetByClient(int clientId) { var orders = await _orderRepo.GetByClientIdAsync(clientId); return Ok(orders); } // Obtener detalle de una orden [HttpGet("{id}")] public async Task GetById(int id) { var order = await _orderRepo.GetByIdAsync(id); if (order == null) return NotFound(); var items = await _orderRepo.GetItemsByOrderIdAsync(id); return Ok(new { Order = order, Items = items }); } }