using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using MealPlanner.Models; using MealPlanner.Services; namespace MealPlanner.Controllers; [ApiController] [Route("api/recipes")] [Authorize] public class RecipeController(RecipeService recipeService) : ControllerBase { private string UserId => User.FindFirst("sub")?.Value ?? throw new UnauthorizedAccessException(); [HttpGet] public async Task GetOwn() { var recipes = await recipeService.GetOwnRecipesAsync(UserId); return Ok(recipes); } [HttpGet("{id:guid}")] public async Task GetById(Guid id) { var recipe = await recipeService.GetByIdOrFetchAsync(id); if (recipe is null) return NotFound(); return Ok(recipe); } [HttpPost] public async Task Create([FromBody] Recipe recipe) { var created = await recipeService.CreateAsync(UserId, recipe); return CreatedAtAction(nameof(GetById), new { id = created.Id }, created); } [HttpPut("{id:guid}")] public async Task Update(Guid id, [FromBody] Recipe recipe) { try { var updated = await recipeService.UpdateAsync(id, UserId, recipe); if (updated is null) return NotFound(); return Ok(updated); } catch (UnauthorizedAccessException) { return Forbid(); } } [HttpDelete("{id:guid}")] public async Task Delete(Guid id) { try { var deleted = await recipeService.DeleteAsync(id, UserId); if (!deleted) return NotFound(); return NoContent(); } catch (UnauthorizedAccessException) { return Forbid(); } } [HttpGet("search")] public async Task Search([FromQuery] string q) { if (string.IsNullOrWhiteSpace(q)) return BadRequest("Query parameter 'q' is required."); var results = await recipeService.SearchAsync(q, UserId); return Ok(results); } }