namespace Health.Application.Users;

public sealed class UserService(
    IUserRepository users,
    IAccountFileCleanup fileCleanup) : IUserService
{
    private readonly IUserRepository _users = users;
    private readonly IAccountFileCleanup _fileCleanup = fileCleanup;

    public async Task<UserProfileDto?> GetProfileAsync(Guid userId, CancellationToken ct)
    {
        var user = await _users.GetAsync(userId, ct);
        return user == null ? null : new UserProfileDto(
            user.Id,
            user.Phone,
            user.Role,
            user.Name,
            user.Gender,
            user.BirthDate?.ToString("yyyy-MM-dd"),
            user.AvatarUrl);
    }

    public async Task<bool> UpdateProfileAsync(Guid userId, UserProfileUpdateRequest request, CancellationToken ct)
    {
        var user = await _users.GetAsync(userId, ct);
        if (user == null) return false;

        if (request.Name != null) user.Name = request.Name;
        if (request.Gender != null) user.Gender = request.Gender;
        if (request.BirthDate.HasValue) user.BirthDate = request.BirthDate.Value;
        user.UpdatedAt = DateTime.UtcNow;
        await _users.SaveChangesAsync(ct);
        return true;
    }

    public async Task DeleteAccountAsync(Guid userId, CancellationToken ct)
    {
        var references = await _users.GetAccountFileReferencesAsync(userId, ct);
        await _fileCleanup.DeleteAsync(userId, references, ct);
        await _users.DeleteAccountDataAsync(userId, ct);
    }
}
