using AuthApi.Models;
using MongoDB.Driver;

namespace AuthApi.Services;

public class UserService
{
    private readonly IMongoCollection<User> _col;

    public UserService(IConfiguration cfg)
    {
        var cs = cfg["MongoDB:ConnectionString"] ?? "mongodb://127.0.0.1:27017";
        var dbName = cfg["MongoDB:DatabaseName"] ?? "GameDb";
        var client = new MongoClient(cs);
        var db = client.GetDatabase(dbName);
        _col = db.GetCollection<User>("Users");

        var keys = Builders<User>.IndexKeys.Ascending(u => u.Username);
        _col.Indexes.CreateOne(new CreateIndexModel<User>(keys, new CreateIndexOptions { Unique = true }));
    }

    public Task<User?> GetByUsernameAsync(string username) =>
        _col.Find(u => u.Username == username).FirstOrDefaultAsync();

    public Task CreateAsync(User user) => _col.InsertOneAsync(user);

    public Task UpdateAsync(User user) =>
        _col.ReplaceOneAsync(u => u.Id == user.Id, user);

    public Task<List<User>> GetAllAsync() =>
        _col.Find(FilterDefinition<User>.Empty).ToListAsync();
}
