using LocationsApi.Models;
using MongoDB.Driver;

namespace LocationsApi.Services;

public class LocationStore
{
    private readonly IMongoCollection<Location> _col;

    public LocationStore(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<Location>("Locations");

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

    public Task CreateAsync(Location location) => _col.InsertOneAsync(location);

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

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

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

    public async Task<bool> UpdateNameAsync(string id, string name)
    {
        var filter = Builders<Location>.Filter.Eq(l => l.Id, id);
        var update = Builders<Location>.Update.Set(l => l.Name, name);
        var result = await _col.UpdateOneAsync(filter, update);
        return result.ModifiedCount > 0;
    }
}
