Files

110 lines
3.0 KiB
C#

using Cloud.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace Cloud.Controllers;
[Authorize]
[ApiController]
[Route("api/[controller]")]
public class DecksController : ControllerBase
{
private readonly AppDbContext _context;
public DecksController(AppDbContext context)
{
_context = context;
}
[HttpGet]
public async Task<ActionResult<List<UserDeck>>> GetDecks()
{
try
{
return Ok(await _context.UserDecks.OrderByDescending(d => d.UpdatedAt).ToListAsync());
}
catch (Exception ex)
{
Console.WriteLine($"[WARNING] Could not retrieve decks: {ex.Message}");
return Ok(new List<UserDeck>());
}
}
[HttpGet("{id:guid}")]
public async Task<ActionResult<UserDeck>> GetDeck(Guid id)
{
try
{
var deck = await _context.UserDecks.FindAsync(id);
if (deck == null) return NotFound();
return Ok(deck);
}
catch (Exception ex)
{
Console.WriteLine($"[WARNING] Could not retrieve deck: {ex.Message}");
return StatusCode(500);
}
}
[HttpPost]
public async Task<ActionResult<UserDeck>> CreateDeck(UserDeck deck)
{
try
{
deck.Id = Guid.NewGuid();
deck.UpdatedAt = DateTime.UtcNow;
_context.UserDecks.Add(deck);
await _context.SaveChangesAsync();
return Ok(deck);
}
catch (Exception ex)
{
Console.WriteLine($"[WARNING] Could not create deck: {ex.Message}");
return StatusCode(500, "Failed to save deck.");
}
}
[HttpPut("{id:guid}")]
public async Task<ActionResult<UserDeck>> UpdateDeck(Guid id, UserDeck deck)
{
try
{
var existing = await _context.UserDecks.FindAsync(id);
if (existing == null) return NotFound();
existing.Name = deck.Name;
existing.Cards = deck.Cards;
existing.Divers = deck.Divers;
existing.Notes = deck.Notes;
existing.Season = deck.Season;
existing.UpdatedAt = DateTime.UtcNow;
await _context.SaveChangesAsync();
return Ok(existing);
}
catch (Exception ex)
{
Console.WriteLine($"[WARNING] Could not update deck: {ex.Message}");
return StatusCode(500, "Failed to update deck.");
}
}
[HttpDelete("{id:guid}")]
public async Task<IActionResult> DeleteDeck(Guid id)
{
try
{
var deck = await _context.UserDecks.FindAsync(id);
if (deck == null) return NotFound();
_context.UserDecks.Remove(deck);
await _context.SaveChangesAsync();
return NoContent();
}
catch (Exception ex)
{
Console.WriteLine($"[WARNING] Could not delete deck: {ex.Message}");
return StatusCode(500);
}
}
}