File size: 2,326 Bytes
202c378
ee79726
 
 
 
 
 
 
202c378
ee79726
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
798b4ec
ee79726
202c378
ee79726
202c378
 
 
 
ee79726
202c378
 
 
 
 
ee79726
202c378
ee79726
202c378
 
 
 
 
 
 
ee79726
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
using LibraryManagement.Shared.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;

namespace Backend.Features.Wallet
{
    [ApiController]
    [Route("api/wallet")]
    [Authorize]
    public class WalletController : ControllerBase
    {
        private readonly IWalletService _walletService;

        public WalletController(IWalletService walletService)
        {
            _walletService = walletService;
        }

        [HttpGet("balance")]
        public async Task<ActionResult<decimal>> GetBalance()
        {
            var userIdStr = User.FindFirstValue(ClaimTypes.NameIdentifier);
            if (string.IsNullOrEmpty(userIdStr)) return Unauthorized();

            var balance = await _walletService.GetBalanceAsync(Guid.Parse(userIdStr));
            return Ok(balance);
        }

        [HttpGet("history")]
        public async Task<ActionResult<IEnumerable<WalletTransactionDto>>> GetHistory()
        {
            var userIdStr = User.FindFirstValue(ClaimTypes.NameIdentifier);
            if (string.IsNullOrEmpty(userIdStr)) return Unauthorized();

            var history = await _walletService.GetHistoryAsync(Guid.Parse(userIdStr));
            return Ok(history);
        }

        [HttpPost("topup")]
        [Authorize(Roles = "Librarian")]
        public async Task<IActionResult> TopUp([FromBody] TopUpRequest request)

        {
            try 
            {
                var librarianIdStr = User.FindFirstValue(ClaimTypes.NameIdentifier);
                if (string.IsNullOrEmpty(librarianIdStr)) return Unauthorized();

                var success = await _walletService.TopUpAsync(
                    request.UserId, 
                    request.Amount, 
                    Guid.Parse(librarianIdStr), 
                    request.Description);

                if (!success) return BadRequest(new { message = "User not found or database error." });

                return Ok(new { message = "Wallet topped up successfully." });
            }
            catch (Exception ex)
            {
                // Return the actual error message to help debug (e.g., missing table error)
                return StatusCode(500, new { message = ex.InnerException?.Message ?? ex.Message });
            }
        }
    }
}