using Microsoft.EntityFrameworkCore;
using Nexus.Api.Data;

namespace Nexus.Api.Repositories;

public sealed class ProjectRepository(NexusDbContext db) : IProjectRepository
{
    public Task<List<Project>> GetAllAsync(CancellationToken ct = default)
        => db.Projects.AsNoTracking().OrderByDescending(x => x.UpdatedAt).ToListAsync(ct);

    public ValueTask<Project?> GetByIdAsync(Guid id, CancellationToken ct = default)
        => db.Projects.FindAsync([id], ct);

    public async Task<Project> AddAsync(Project project, CancellationToken ct = default)
    {
        db.Projects.Add(project);
        await db.SaveChangesAsync(ct);
        return project;
    }

    public async Task UpdateAsync(Project project, CancellationToken ct = default)
    {
        project.UpdatedAt = DateTimeOffset.UtcNow;
        await db.SaveChangesAsync(ct);
    }

    public async Task DeleteAsync(Project project, CancellationToken ct = default)
    {
        db.Projects.Remove(project);
        await db.SaveChangesAsync(ct);
    }

    public Task<bool> HasTasksAsync(Guid projectId, CancellationToken ct = default)
        => db.Tasks.AnyAsync(t => t.ProjectId == projectId, ct);
}
