-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSelectionsController.cs
More file actions
257 lines (223 loc) · 8.06 KB
/
SelectionsController.cs
File metadata and controls
257 lines (223 loc) · 8.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
using F1.Core.Dtos;
using F1.Core.Interfaces;
using F1.Core.Models;
using F1.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using System.Collections.Concurrent;
using System.Security.Claims;
namespace F1.Api.Controllers;
[ApiController]
[Route("selections")]
public class SelectionsController : ControllerBase
{
private static readonly ConcurrentDictionary<string, Selection> MockSelections = new(StringComparer.OrdinalIgnoreCase);
private readonly ISelectionService _selectionService;
private readonly IConfiguration _configuration;
private readonly IHostEnvironment _hostEnvironment;
public SelectionsController(
ISelectionService selectionService,
IConfiguration configuration,
IHostEnvironment hostEnvironment)
{
_selectionService = selectionService;
_configuration = configuration;
_hostEnvironment = hostEnvironment;
}
[HttpGet("{raceId}/config")]
public IActionResult GetConfig(string raceId)
{
var config = _selectionService.GetRaceConfig(raceId);
if (config is null)
{
return NotFound();
}
return Ok(config);
}
[HttpGet("{raceId}/mine")]
public async Task<IActionResult> GetMine(string raceId)
{
var userId = ResolveUserId();
if (string.IsNullOrWhiteSpace(userId))
{
return Unauthorized();
}
if (ShouldUseMockCurrentSelections())
{
return Ok(GetOrCreateMockSelection(raceId, userId));
}
var selection = await _selectionService.GetSelectionAsync(raceId, userId);
if (selection is null)
{
return NotFound();
}
return Ok(selection);
}
[HttpGet("current")]
public async Task<IActionResult> GetCurrent()
{
var userId = ResolveUserId();
if (string.IsNullOrWhiteSpace(userId))
{
return Unauthorized();
}
if (ShouldUseMockCurrentSelections())
{
var selection = GetOrCreateMockSelection(SelectionService.AustraliaRaceId2026, userId);
return Ok(MapCurrentSelections(selection));
}
var selections = await _selectionService.GetCurrentSelectionsAsync(userId);
return Ok(selections);
}
[HttpPut("{raceId}/mine")]
public async Task<IActionResult> UpsertMine(string raceId, [FromBody] SelectionSubmissionDto submission)
{
var userId = ResolveUserId();
if (string.IsNullOrWhiteSpace(userId))
{
return Unauthorized();
}
if (ShouldUseMockCurrentSelections())
{
var validationMessage = ValidateMockSubmission(submission);
if (validationMessage is not null)
{
return BadRequest(new { message = validationMessage });
}
var selection = UpsertMockSelection(raceId, userId, submission);
return Ok(selection);
}
try
{
var selection = await _selectionService.UpsertSelectionAsync(raceId, userId, submission);
return Ok(selection);
}
catch (SelectionValidationException ex)
{
return BadRequest(new { message = ex.Message });
}
catch (SelectionForbiddenException ex)
{
return StatusCode(StatusCodes.Status403Forbidden, new { message = ex.Message });
}
}
private string? ResolveUserId()
{
return User.FindFirstValue(ClaimTypes.Email)
?? Request.Headers["Cf-Access-Authenticated-User-Email"].FirstOrDefault();
}
private bool ShouldUseMockCurrentSelections()
{
return _hostEnvironment.IsDevelopment()
&& _configuration.GetValue<bool>("DevSettings:MockCurrentSelections");
}
private static Selection GetOrCreateMockSelection(string raceId, string userId)
{
var key = BuildMockSelectionKey(raceId, userId);
return MockSelections.GetOrAdd(key, _ => BuildDefaultMockSelection(raceId, userId));
}
private static Selection UpsertMockSelection(string raceId, string userId, SelectionSubmissionDto submission)
{
var orderedSelections = submission.OrderedSelections;
var key = BuildMockSelectionKey(raceId, userId);
var updated = new Selection
{
Id = MockSelections.TryGetValue(key, out var existing) ? existing.Id : Guid.NewGuid(),
RaceId = raceId,
UserId = userId,
OrderedSelections = orderedSelections,
BetType = submission.BetType,
SubmittedAtUtc = DateTime.UtcNow,
IsLocked = false
};
MockSelections[key] = updated;
return updated;
}
private static Selection BuildDefaultMockSelection(string raceId, string userId)
{
return new Selection
{
Id = Guid.NewGuid(),
RaceId = raceId,
UserId = userId,
BetType = BetType.Regular,
SubmittedAtUtc = new DateTime(2026, 3, 6, 9, 0, 0, DateTimeKind.Utc),
IsLocked = false,
OrderedSelections =
[
new SelectionPosition { Position = 1, DriverId = "max_verstappen" },
new SelectionPosition { Position = 2, DriverId = "lando_norris" },
new SelectionPosition { Position = 3, DriverId = "charles_leclerc" },
new SelectionPosition { Position = 4, DriverId = "oscar_piastri" },
new SelectionPosition { Position = 5, DriverId = "lewis_hamilton" }
]
};
}
private static IReadOnlyList<CurrentSelectionDto> MapCurrentSelections(Selection selection)
{
var userName = selection.UserId.Split('@')[0];
var orderedSelections = selection.OrderedSelections;
var rows = new List<CurrentSelectionDto>(orderedSelections.Count);
foreach (var selectionItem in orderedSelections)
{
var driverId = selectionItem.DriverId;
if (string.IsNullOrWhiteSpace(driverId))
{
continue;
}
rows.Add(new CurrentSelectionDto
{
Position = selectionItem.Position,
UserId = selection.UserId,
UserName = userName,
DriverId = driverId,
DriverName = ResolveMockDriverName(driverId),
SelectionType = selection.BetType.ToString(),
Timestamp = selection.SubmittedAtUtc
});
}
return rows;
}
private static string ResolveMockDriverName(string driverId)
{
return driverId switch
{
"max_verstappen" => "Max Verstappen",
"lando_norris" => "Lando Norris",
"charles_leclerc" => "Charles Leclerc",
"oscar_piastri" => "Oscar Piastri",
"lewis_hamilton" => "Lewis Hamilton",
"leclerc" => "Charles Leclerc",
"norris" => "Lando Norris",
"hamilton" => "Lewis Hamilton",
"piastri" => "Oscar Piastri",
_ => driverId
};
}
private static string? ValidateMockSubmission(SelectionSubmissionDto submission)
{
var orderedSelections = submission.OrderedSelections;
var distinctCount = orderedSelections
.Select(item => item.DriverId)
.Distinct(StringComparer.OrdinalIgnoreCase)
.Count();
var distinctPositions = orderedSelections
.Select(item => item.Position)
.Distinct()
.Count();
if (orderedSelections.Count != 5 || distinctCount != 5 || distinctPositions != 5)
{
return "Exactly 5 unique drivers must be selected.";
}
if (orderedSelections.Any(item => item.Position < 1 || item.Position > 5))
{
return "Selection positions must be between 1 and 5.";
}
return null;
}
private static string BuildMockSelectionKey(string raceId, string userId)
{
return $"{raceId}::{userId}";
}
}