using CharacterApi.Models;
using MongoDB.Driver;

namespace CharacterApi.Services;

public class CharacterStore
{
    private readonly IMongoCollection<Character> _col;

    public CharacterStore(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<Character>("Characters");

        var ownerIndex = Builders<Character>.IndexKeys.Ascending(c => c.OwnerUserId);
        _col.Indexes.CreateOne(new CreateIndexModel<Character>(ownerIndex));
    }

    public Task CreateAsync(Character character) => _col.InsertOneAsync(character);

    public Task<List<Character>> GetForOwnerAsync(string ownerUserId) =>
        _col.Find(c => c.OwnerUserId == ownerUserId).ToListAsync();

    public async Task<bool> DeleteForOwnerAsync(string id, string ownerUserId, bool allowAnyOwner)
    {
        var filter = Builders<Character>.Filter.Eq(c => c.Id, id);
        if (!allowAnyOwner)
        {
            filter = Builders<Character>.Filter.And(
                filter,
                Builders<Character>.Filter.Eq(c => c.OwnerUserId, ownerUserId)
            );
        }

        var result = await _col.DeleteOneAsync(filter);
        return result.DeletedCount > 0;
    }
}
