using Adapters.Driven.Persistence.Context;
using Domain.Entities;
using Domain.Ports.Repositories;
using Microsoft.EntityFrameworkCore;

namespace Adapters.Driven.Persistence.Repositories;

public class UserRepository(AppDbContext context) : IUserRepository
{
    public async Task<User?> GetByIdAsync(int id, CancellationToken ct = default)
    {
        return await context.Users
            .Include(u => u.Student)
            .FirstOrDefaultAsync(u => u.Id == id, ct);
    }

    public async Task<User?> GetByUsernameAsync(string username, CancellationToken ct = default)
    {
        return await context.Users
            .Include(u => u.Student)
            .FirstOrDefaultAsync(u => u.Username == username.ToLowerInvariant(), ct);
    }

    public async Task<User> AddAsync(User user, CancellationToken ct = default)
    {
        await context.Users.AddAsync(user, ct);
        return user;
    }

    public async Task<bool> ExistsAsync(string username, CancellationToken ct = default)
    {
        return await context.Users
            .AnyAsync(u => u.Username == username.ToLowerInvariant(), ct);
    }

    public Task UpdateAsync(User user, CancellationToken ct = default)
    {
        context.Users.Update(user);
        return Task.CompletedTask;
    }
}
