using LocationsApi.Models; using MongoDB.Driver; namespace LocationsApi.Services; public class UnitTrainingService { private const string ScoutUnitType = "Scout"; private const string ArcherUnitType = "Archer"; private readonly IMongoCollection _training; private readonly IMongoCollection _units; private readonly IMongoCollection _locations; private readonly ResourceService _resources; private readonly GameSettingsService _settings; private readonly int _scoutGoldCost; private readonly int _archerGoldCost; private readonly int _archerWoodCost; private readonly int _defaultScoutTrainingSeconds; private readonly int _defaultArcherTrainingSeconds; private readonly int _visibilityDepth; public UnitTrainingService(IConfiguration cfg, ResourceService resources, GameSettingsService settings) { var connectionString = cfg["MongoDB:ConnectionString"] ?? "mongodb://127.0.0.1:27017"; var databaseName = cfg["MongoDB:DatabaseName"] ?? "territory-autobattler"; var client = new MongoClient(connectionString); var database = client.GetDatabase(databaseName); _training = database.GetCollection("UnitTraining"); _units = database.GetCollection("Units"); _locations = database.GetCollection("Locations"); _resources = resources; _settings = settings; _scoutGoldCost = int.TryParse(cfg["Units:ScoutGoldCost"], out var scoutGoldCost) ? Math.Max(0, scoutGoldCost) : 50; _archerGoldCost = int.TryParse(cfg["Units:ArcherGoldCost"], out var archerGoldCost) ? Math.Max(0, archerGoldCost) : 100; _archerWoodCost = int.TryParse(cfg["Units:ArcherWoodCost"], out var archerWoodCost) ? Math.Max(0, archerWoodCost) : 100; _defaultScoutTrainingSeconds = int.TryParse(cfg["Units:ScoutTrainingSeconds"], out var scoutTrainingSeconds) ? Math.Max(1, scoutTrainingSeconds) : 60; _defaultArcherTrainingSeconds = int.TryParse(cfg["Units:ArcherTrainingSeconds"], out var archerTrainingSeconds) ? Math.Max(1, archerTrainingSeconds) : 60; _visibilityDepth = int.TryParse(cfg["World:VisibilityDepth"], out var visibilityDepth) ? Math.Max(0, visibilityDepth) : 3; _training.Indexes.CreateOne(new CreateIndexModel( Builders.IndexKeys.Ascending(x => x.Username).Ascending(x => x.Status))); _units.Indexes.CreateOne(new CreateIndexModel( Builders.IndexKeys.Ascending(x => x.Username).Ascending(x => x.UnitType))); _units.Indexes.CreateOne(new CreateIndexModel( Builders.IndexKeys.Ascending(x => x.SourceTrainingId), new CreateIndexOptions { Unique = true, Sparse = true })); } public async Task GetMineAsync(string username) { await CompleteFinishedTrainingAsync(username); await _training.DeleteManyAsync(x => x.Username == username && x.Status == "Consumed"); var allTraining = await _training.Find(x => x.Username == username).ToListAsync(); var allUnits = await _units.Find(x => x.Username == username).ToListAsync(); var completedScouts = allTraining.Count(x => x.UnitType == ScoutUnitType && x.Status == "Completed"); var completedArchers = allUnits.Count(x => x.UnitType == ArcherUnitType); var activeTraining = allTraining .Where(x => x.Status == "Training") .OrderBy(x => x.CompletesAtUtc) .Select(UnitTrainingResponse.FromTraining) .ToList(); return new PlayerUnitsResponse { CompletedScouts = completedScouts, CompletedArchers = completedArchers, Training = activeTraining, Units = allUnits .OrderBy(x => x.Q) .ThenBy(x => x.R) .ThenBy(x => x.CreatedAtUtc) .Select(UnitInstanceResponse.FromUnit) .ToList() }; } public async Task TrainAsync(string username, TrainUnitRequest request) { var normalizedUnitType = NormalizeUnitType(request.UnitType); if (normalizedUnitType is null) { throw new ArgumentException("Unsupported unit type.", nameof(request.UnitType)); } Location? origin = null; if (normalizedUnitType == ArcherUnitType) { if (request.Q is null || request.R is null) { throw new InvalidOperationException("Select a completed Barracks to train Archers."); } origin = await GetBuiltBarracksAsync(username, request.Q.Value, request.R.Value); if (origin is null) { throw new InvalidOperationException("A completed Barracks is required to train Archers."); } } var goldCost = normalizedUnitType == ArcherUnitType ? _archerGoldCost : _scoutGoldCost; var woodCost = normalizedUnitType == ArcherUnitType ? _archerWoodCost : 0; var spent = normalizedUnitType == ArcherUnitType ? await _resources.TrySpendResourcesAsync(username, goldCost, woodCost, 0) : await _resources.TrySpendGoldAsync(username, goldCost); if (!spent) { return null; } var now = DateTime.UtcNow; var trainingSeconds = normalizedUnitType == ArcherUnitType ? await _settings.GetIntAsync(GameSettingsService.ArcherTrainingSeconds, _defaultArcherTrainingSeconds) : await _settings.GetIntAsync(GameSettingsService.ScoutTrainingSeconds, _defaultScoutTrainingSeconds); var training = new UnitTraining { Username = username, UnitType = normalizedUnitType, GoldCost = goldCost, WoodCost = woodCost, OriginQ = origin?.Q, OriginR = origin?.R, Status = "Training", StartedAtUtc = now, CompletesAtUtc = now.AddSeconds(trainingSeconds), CreatedAtUtc = now, UpdatedAtUtc = now }; await _training.InsertOneAsync(training); return training; } public async Task> MoveSquadAsync(string username, MoveUnitSquadRequest request) { var normalizedUnitType = NormalizeUnitType(request.UnitType); if (normalizedUnitType != ArcherUnitType) { throw new ArgumentException("Only Archer squads can be moved right now.", nameof(request.UnitType)); } if (request.FromQ == request.ToQ && request.FromR == request.ToR) { throw new InvalidOperationException("Select a different destination tile."); } if (!await CanMoveToAsync(username, request.ToQ, request.ToR)) { throw new InvalidOperationException("Archers can only move to visible non-rival tiles."); } var now = DateTime.UtcNow; var units = await _units.Find(x => x.Username == username && x.UnitType == ArcherUnitType && x.Q == request.FromQ && x.R == request.FromR) .ToListAsync(); if (units.Count == 0) { return []; } await _units.UpdateManyAsync( x => x.Username == username && x.UnitType == ArcherUnitType && x.Q == request.FromQ && x.R == request.FromR, Builders.Update .Set(x => x.Q, request.ToQ) .Set(x => x.R, request.ToR) .Set(x => x.Status, "Idle") .Set(x => x.UpdatedAtUtc, now)); return await _units.Find(x => x.Username == username && x.UnitType == ArcherUnitType && x.Q == request.ToQ && x.R == request.ToR) .ToListAsync(); } private async Task GetBuiltBarracksAsync(string username, int q, int r) { await CompleteFinishedBuildingsAsync(username); return await _locations.Find(x => x.OwnerUsername == username && x.Q == q && x.R == r && x.BuildingType == "Barracks" && (x.BuildingStatus == "Built" || x.BuildingStatus == null || x.BuildingStatus == "")) .FirstOrDefaultAsync(); } private async Task CompleteFinishedBuildingsAsync(string username) { var now = DateTime.UtcNow; var update = Builders.Update .Set(x => x.BuildingStatus, "Built") .Set(x => x.BuildingBuiltAtUtc, now) .Set(x => x.UpdatedAtUtc, now); await _locations.UpdateManyAsync( x => x.OwnerUsername == username && x.BuildingType == "Barracks" && x.BuildingStatus == "Building" && x.BuildingCompletesAtUtc <= now, update); } private async Task CanMoveToAsync(string username, int q, int r) { var ownedLocations = await _locations.Find(x => x.OwnerUsername == username).ToListAsync(); if (!ownedLocations.Any(owned => HexDistance(owned.Q, owned.R, q, r) <= _visibilityDepth)) { return false; } var target = await _locations.Find(x => x.Q == q && x.R == r).FirstOrDefaultAsync(); return target is null || string.IsNullOrWhiteSpace(target.OwnerUsername) || string.Equals(target.OwnerUsername, username, StringComparison.OrdinalIgnoreCase); } private static int HexDistance(int q1, int r1, int q2, int r2) { var s1 = -q1 - r1; var s2 = -q2 - r2; return Math.Max(Math.Max(Math.Abs(q1 - q2), Math.Abs(r1 - r2)), Math.Abs(s1 - s2)); } public async Task TryConsumeCompletedScoutAsync(string username) { await CompleteFinishedTrainingAsync(username); var consumed = await _training.FindOneAndDeleteAsync( x => x.Username == username && x.UnitType == ScoutUnitType && x.Status == "Completed", new FindOneAndDeleteOptions { Sort = Builders.Sort.Ascending(x => x.CompletedAtUtc).Ascending(x => x.CreatedAtUtc) }); return consumed is not null; } public async Task HasCompletedScoutAsync(string username) { await CompleteFinishedTrainingAsync(username); return await _training.Find(x => x.Username == username && x.UnitType == ScoutUnitType && x.Status == "Completed").AnyAsync(); } private async Task CompleteFinishedTrainingAsync(string username) { var now = DateTime.UtcNow; var readyTraining = await _training.Find(x => x.Username == username && x.Status == "Training" && x.CompletesAtUtc <= now) .ToListAsync(); foreach (var training in readyTraining) { var update = Builders.Update .Set(x => x.Status, "Completed") .Set(x => x.CompletedAtUtc, now) .Set(x => x.UpdatedAtUtc, now); var completed = await _training.FindOneAndUpdateAsync( x => x.Id == training.Id && x.Status == "Training", update, new FindOneAndUpdateOptions { ReturnDocument = ReturnDocument.After }); if (completed is null || completed.UnitType != ArcherUnitType) { continue; } var unit = new UnitInstance { Username = completed.Username, UnitType = ArcherUnitType, Q = completed.OriginQ ?? 0, R = completed.OriginR ?? 0, Status = "Idle", SourceTrainingId = completed.Id, CreatedAtUtc = now, UpdatedAtUtc = now }; try { await _units.InsertOneAsync(unit); } catch (MongoWriteException) { } } } private static string? NormalizeUnitType(string unitType) { var trimmed = unitType.Trim(); return trimmed.ToLowerInvariant() switch { "scout" => ScoutUnitType, "archer" => ArcherUnitType, _ => null }; } }