71 lines
2.0 KiB
C#
71 lines
2.0 KiB
C#
using Backend.DatabaseHandler;
|
|
using Backend.Interface;
|
|
using Backend.ServiceHandler;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
|
|
namespace Backend.Controllers
|
|
{
|
|
[ApiController]
|
|
[Route("api/weather")]
|
|
public sealed class WeatherController : ControllerBase
|
|
{
|
|
private readonly IUserLocationStore _locationStore;
|
|
private readonly WeatherService _weather;
|
|
|
|
public WeatherController(IUserLocationStore locationStore, WeatherService weather)
|
|
{
|
|
_locationStore = locationStore;
|
|
_weather = weather;
|
|
}
|
|
|
|
[HttpPut("set-location")]
|
|
public async Task<IActionResult> SetLocation(
|
|
[FromQuery] string user,
|
|
[FromQuery] string city,
|
|
CancellationToken cancellationToken = default)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(user))
|
|
return BadRequest("User cannot be empty.");
|
|
if (string.IsNullOrWhiteSpace(city))
|
|
return BadRequest("City cannot be empty.");
|
|
|
|
var geo = await _weather.GeocodeAsync(city, cancellationToken);
|
|
if (geo is null)
|
|
return BadRequest("City not found.");
|
|
|
|
var (resolvedCity, lat, lng) = geo.Value;
|
|
|
|
await _locationStore.UpsertAsync(new UserLocationRecord
|
|
{
|
|
Username = user.Trim(),
|
|
City = resolvedCity,
|
|
Latitude = lat,
|
|
Longitude = lng
|
|
}, cancellationToken);
|
|
|
|
return Ok(new { city = resolvedCity, latitude = lat, longitude = lng });
|
|
}
|
|
|
|
[HttpGet("current")]
|
|
public async Task<IActionResult> GetCurrent(
|
|
[FromQuery] string user,
|
|
CancellationToken cancellationToken = default)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(user))
|
|
return BadRequest("User cannot be empty.");
|
|
|
|
var location = await _locationStore.GetAsync(user.Trim(), cancellationToken);
|
|
if (location is null)
|
|
return BadRequest("No location set. Use /api/weather/set-location first.");
|
|
|
|
var weather = await _weather.GetCurrentWeatherAsync(
|
|
location.Latitude, location.Longitude, cancellationToken);
|
|
|
|
if (weather is null)
|
|
return StatusCode(500, new { error = "Failed to fetch weather data." });
|
|
|
|
return Ok(CurrentWeatherResponse.From(location, weather));
|
|
}
|
|
}
|
|
}
|