using eprintServer.Entities; using eprintServer.Requests; using eprintServer.Responses; using eprintServer.Services; using eprintServer.Enums; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; [ApiController] [Route("api/[controller]")] [Authorize(Roles = "ADMIN,SUB_ADMIN,USER")] public class PaymentController : ControllerBase { private readonly IPaymentService _paymentService; private readonly ThawaniServices _thawaniServices; public PaymentController(IPaymentService paymentService, ThawaniServices thawaniServices) { _paymentService = paymentService; _thawaniServices = thawaniServices; } [HttpGet("get-payment-by-id/{id}")] public async Task GetById(long id) { var payment = await _paymentService.GetPaymentById(id); return payment == null ? NotFound() : Ok(payment); } [HttpGet("all-payments-list")] public async Task GetAll() => Ok(await _paymentService.GetAllPayments()); [HttpPost("add-payment")] public async Task Add([FromBody] PaymentRequest req) { // If binding fails, req.OrderId will be 0 if (req.OrderId <= 0) { return BadRequest(new { error = "OrderId is required and must be greater than 0" }); } try { var result = await _paymentService.AddPaymentToOrder( req.OrderId, req.Amount, req.Discount, req.Currency ); return Ok(result); } catch (Exception ex) { return BadRequest(new { error = ex.Message }); } } [HttpDelete("delete-payment{id}")] public async Task Delete(long id) => await _paymentService.DeletePayment(id) ? NoContent() : NotFound(); [HttpPatch("update-payment-status/{id}")] public async Task UpdateStatus(long id, [FromBody] PaymentStatus status) { var updatedPayment = await _paymentService.UpdateStatus(id, status); if (updatedPayment == null) { return NotFound(new { Message = $"Payment with ID {id} not found." }); } return Ok(updatedPayment); } [HttpPost("thawani-pay-order")] public async Task InitiateOrderPayment([FromBody] ThawaniOrderPaymentRequest request) { if (request.OrderId <= 0) return BadRequest("A valid Order ID is required."); try { var redirectUrl = await _paymentService.PayOrderWithThawani( request.OrderId, request.UnitAmount.Value, request.SuccessUrl, request.CancelUrl ); return Ok(new { url = redirectUrl }); } catch (HttpRequestException ex) { // LOGGING: This is where you log the actual Thawani error to your server // _logger.LogError("Thawani API Error: {Message}", ex.Message); return StatusCode(400, new { message = "Thawani Provider Error", detail = ex.Message // This will contain the "Invalid information" reason }); } catch (Exception ex) { return StatusCode(500, new { message = ex.Message }); } } }