// MealMenuApiController.cs
using Aberwyn.Models;
using Aberwyn.Data;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;

namespace Aberwyn.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class MealMenuApiController : ControllerBase
    {
        private readonly MenuService _menuService;

        public MealMenuApiController(MenuService menuService, IConfiguration configuration, IHostEnvironment env)
        {
            _menuService = menuService;
        }

        [HttpGet("menu")]
        public IActionResult GetMenu(int weekNumber, int year)
        {
            var menu = _menuService.GetWeeklyMenu(weekNumber, year);
            return Ok(menu ?? new List<WeeklyMenu>());
        }

        [HttpGet("getMeals")]
        public IActionResult GetMeals()
        {
            var meals = _menuService.GetMealsDetailed(); // Hämtar med ImageData
            var mealDtos = meals.Select(MealDto.FromMeal).ToList();
            return Ok(mealDtos);
        }


        [HttpPut("menu")]
        public IActionResult SaveMenu([FromBody] MenuViewModel weeklyMenu)
        {
            _menuService.UpdateWeeklyMenu(weeklyMenu);
            return Ok("Menu saved successfully");
        }

        [HttpPost("addMeal")]
        public IActionResult AddMeal([FromBody] Meal meal)
        {
            if (meal == null || string.IsNullOrWhiteSpace(meal.Name))
                return BadRequest("Meal Name is required.");

            // Använd AddMeal som returnerar det nya ID:t
            var mealId = _menuService.AddMeal(meal);

            if (mealId > 0)
                return Ok(new { Message = "Meal added successfully", MealId = mealId });

            return StatusCode(500, "Failed to add meal.");
        }
    }
}
