// MealMenuApiController.cs
using Aberwyn.Data;
using Aberwyn.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using System.Net.Http.Headers;
using System.Text.Json;

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("getPublishedMeals")]
        public IActionResult GetPublishedMeals([FromQuery] bool includeUnpublished = false)
        {
            var meals = _menuService.GetMeals()
                .Where(m => includeUnpublished || m.IsPublished)
                .Select(m => new {
                    m.Id,
                    m.Name,
                    m.Description,
                    ThumbnailData = m.ThumbnailData != null ? Convert.ToBase64String(m.ThumbnailData) : null
                })
                .ToList();

            return Ok(meals);
        }



        [HttpGet("getMeals")]
        public IActionResult GetMeals()
        {
            var meals = _menuService.GetMealsSlim(true);
            var mealDtos = meals.Select(m => MealDto.FromMeal(m, includeThumbnail: true)).ToList(); // 👈 fix
            return Ok(mealDtos);
        }


        [HttpGet("getWeeklyMenu")]
        public IActionResult GetWeeklyMenu(int weekNumber, int year)
        {
            var menuDtos = _menuService.GetWeeklyMenuDto(weekNumber, year);
            Console.WriteLine("Hämtar meals: " + menuDtos);
            return Ok(menuDtos);
        }


        [HttpGet("today")]
        public IActionResult GetTodayMenu()
        {
            var today = DateTime.Today;
            var menu = _menuService.GetMenuForDate(today);

            if (menu == null)
                return NotFound(new { message = "Ingen meny hittades för idag." });

            return Ok(new
            {
                date = today.ToString("yyyy-MM-dd"),
                lunch = menu.LunchMealName ?? "",
                dinner = menu.DinnerMealName ?? "",
                breakfast = menu.BreakfastMealName ?? ""
            });
        }


        [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.");
        }





        #region Skolmat
        [HttpGet("skolmat")]
public async Task<IActionResult> GetSkolmat(int week, [FromQuery] string sensor = "sensor.engelbrektsskolan")
{
    var token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiI3M2Q5ODIyYzU4ZWI0MjM4OWEyMGQ2MWQ2MWVhOWYzYyIsImlhdCI6MTc0OTE1MzY1MCwiZXhwIjoyMDY0NTEzNjUwfQ.8C_dKm7P1BbFVJKc_wT76YnQqiZxkP9EzrsLbfD0Ml8";
    var client = new HttpClient();
    client.BaseAddress = new Uri("http://192.168.1.196:8123/");
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

    var res = await client.GetAsync($"/api/states/{sensor}");

    if (!res.IsSuccessStatusCode)
        return StatusCode((int)res.StatusCode, $"Kunde inte hämta data för {sensor}");

    var json = await res.Content.ReadAsStringAsync();
    var doc = JsonDocument.Parse(json);

    var attr = doc.RootElement.GetProperty("attributes");

    if (!attr.TryGetProperty("calendar", out var calendar))
        return NotFound("Ingen kalender hittades i attributen");

    if (!calendar.TryGetProperty(week.ToString(), out var weekData))
        return NotFound("Ingen skolmat för vecka " + week);

    var result = new List<object>();
    foreach (var day in weekData.EnumerateArray())
    {
        var weekday = day.GetProperty("weekday").GetString();
        var date = day.GetProperty("date").GetString();
        var courses = day.GetProperty("courses").EnumerateArray().Select(c => c.GetString()).ToList();

        result.Add(new { weekday, date, courses });
    }

    return Ok(result);
}
        #endregion
    }
}
