SoftTraderBackend/Controller/WeatherController.cs
2026-03-20 10:42:48 -04:00

93 lines
2.4 KiB
C#

using Backend.DatabaseHandler;
using Backend.Interface;
using Backend.ServiceHander;
using Microsoft.AspNetCore.Mvc;
namespace Backend.Controller
{
[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;
}
[HttpGet("set-location")]
public async Task<IActionResult> SetLocation(
[FromQuery] string user,
[FromQuery] string city,
CancellationToken cancellationToken = default)
{
try
{
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 });
}
catch (Exception ex)
{
return StatusCode(500, new { error = ex.ToString() });
}
}
[HttpGet("current")]
public async Task<IActionResult> GetCurrent(
[FromQuery] string user,
CancellationToken cancellationToken = default)
{
try
{
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(new
{
city = location.City,
temperatureF = weather.TemperatureF,
humidityPercent = weather.HumidityPercent,
windSpeedMph = weather.WindSpeedMph,
weatherCode = weather.WeatherCode,
description = weather.Description
});
}
catch (Exception ex)
{
return StatusCode(500, new { error = ex.ToString() });
}
}
}
}