using Aberwyn.Data;
using Aberwyn.Models; // Byt till din namespace
using Humanizer;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Security.Claims;


[ApiController]
[Route("api/[controller]")]
public class MealWishController : ControllerBase
{
    private readonly ApplicationDbContext _context;

    public MealWishController(ApplicationDbContext context)
    {
        _context = context;
    }

    // 1. Skapa en ny önskan
    [HttpPost("create")]
    public async Task<ActionResult<MealWishDto>> Create([FromBody] CreateMealWishDto dto)
    {
        var wish = new MealWish
        {
            Name = dto.Name,
            Recipe = dto.Recipe
        };

        var userId = User.FindFirstValue(ClaimTypes.NameIdentifier) ?? "anonymous";
        wish.RequestedByUserId = userId;
        wish.CreatedAt = DateTime.UtcNow;
        wish.IsArchived = false;
        wish.IsImported = false;

        _context.MealWishes.Add(wish);
        await _context.SaveChangesAsync();

        return Ok(MealWishDto.FromEntity(wish)); // ✅ returnera DTO
    }

    // 2. Hämta alla önskningar (admin)
    [HttpGet("all")]
    public async Task<IActionResult> GetAll(bool includeArchived = false)
    {
        var wishes = await _context.MealWishes
            .Include(w => w.RequestedByUser)  // hämta användaren
            .Where(w => includeArchived || !w.IsArchived)
            .OrderByDescending(w => w.CreatedAt)
            .Select(w => new {
                w.Id,
                w.Name,
                w.Recipe,
                RequestedByUserName = w.RequestedByUser != null ? w.RequestedByUser.UserName : "Okänd",
                CreatedAt = w.CreatedAt.ToLocalTime().ToString("yyyy-MM-dd HH:mm"), 
                w.IsArchived,
                w.IsImported
            })
            .ToListAsync();

        return Ok(wishes);
    }


    // 3. Avfärda / arkivera
    [HttpPost("{id}/archive")]
    public async Task<IActionResult> Archive(int id)
    {
        var wish = await _context.MealWishes.FindAsync(id);
        if (wish == null) return NotFound();

        wish.IsArchived = true;
        await _context.SaveChangesAsync();

        return Ok(wish);
    }

    // 4. Importera till Meals
    [HttpPost("{id}/import")]
    public async Task<IActionResult> Import(int id)
    {
        var wish = await _context.MealWishes.FindAsync(id);
        if (wish == null) return NotFound();

        if (wish.IsImported)
            return BadRequest("Denna rätt har redan importerats.");

        // Skapa en ny Meal
        var meal = new Meal
        {
            Name = wish.Name,
            Instructions = wish.Recipe,
            IsAvailable = true,
            CreatedAt = DateTime.UtcNow,
            IsPublished = false
        };

        _context.Meals.Add(meal);
        await _context.SaveChangesAsync();

        wish.LinkedMealId = meal.Id;
        wish.IsImported = true;
        wish.IsArchived = true;
        await _context.SaveChangesAsync();

        return Ok(wish);
    }

    [HttpGet("search")]
    public async Task<IActionResult> Search([FromQuery] string name)
    {
        if (string.IsNullOrWhiteSpace(name)) return BadRequest();

        var meals = await _context.Meals
            .Where(m => m.Name.Contains(name))
            .OrderBy(m => m.Name)
            .Take(10)
            .Select(m => new { m.Id, m.Name })
            .ToListAsync();

        return Ok(meals);
    }
}
