using Aberwyn.Data;
using Aberwyn.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace Aberwyn.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class MealRatingApiController : ControllerBase
    {
        private readonly ApplicationDbContext _context;
        private readonly UserManager<ApplicationUser> _userManager;

        public MealRatingApiController(ApplicationDbContext context, UserManager<ApplicationUser> userManager)
        {
            _context = context;
            _userManager = userManager;
        }

        [HttpGet("{mealId}")]
        public async Task<IActionResult> GetRating(int mealId)
        {
            var user = await _userManager.GetUserAsync(User);
            if (user == null) return Unauthorized();

            var rating = await _context.MealRatings
                .FirstOrDefaultAsync(r => r.MealId == mealId && r.UserId == user.Id);

            return Ok(rating?.Rating ?? 0);
        }
        [HttpGet("average/{mealId}")]
        public async Task<IActionResult> GetAverageRating(int mealId)
        {
            var ratings = await _context.MealRatings
                .Where(r => r.MealId == mealId)
                .ToListAsync();

            if (ratings.Count == 0)
                return Ok(0);

            var avg = ratings.Average(r => r.Rating);
            return Ok(avg);
        }


        [HttpPost]
        public async Task<IActionResult> SetRating([FromBody] MealRatingDto model)
        {
            var user = await _userManager.GetUserAsync(User);
            if (user == null) return Unauthorized();

            var existing = await _context.MealRatings
                .FirstOrDefaultAsync(r => r.MealId == model.MealId && r.UserId == user.Id);

            if (existing != null)
            {
                existing.Rating = model.Rating;
                existing.CreatedAt = DateTime.UtcNow;
            }
            else
            {
                _context.MealRatings.Add(new MealRating
                {
                    MealId = model.MealId,
                    UserId = user.Id,
                    Rating = model.Rating,
                    CreatedAt = DateTime.UtcNow
                });
            }

            await _context.SaveChangesAsync();
            return Ok();
        }

    }

}
