using Microsoft.EntityFrameworkCore;
using TaskLedger.Api.Domain.Entities;
using TaskLedger.Api.Infrastructure.Data;
namespace TaskLedger.Api.Services;
///
/// Service implementation for task operations.
///
public class TaskService : ITaskService
{
private readonly AppDbContext _context;
///
/// Initializes a new instance of the class.
///
/// The database context.
public TaskService(AppDbContext context)
{
_context = context;
}
///
public async Task CreateTaskAsync(string title, string? description)
{
// Business rule: Title is required
if (string.IsNullOrWhiteSpace(title))
{
throw new ArgumentException("Title is required.", nameof(title));
}
// Create new task entity
var task = new Domain.Entities.Task
{
Title = title.Trim(),
Description = description?.Trim(),
IsCompleted = false,
CreatedUtc = DateTime.UtcNow // Business rule: CreatedUtc is set server-side
};
// Add to context and save
_context.Tasks.Add(task);
await _context.SaveChangesAsync();
return task;
}
///
public async Task> GetAllTasksAsync()
{
return await _context.Tasks
.OrderBy(t => t.CreatedUtc)
.ToListAsync();
}
}