using System.ComponentModel.DataAnnotations;
using CafeCritic.Context;
using CafeCritic.Enums;
using CafeCritic.Mappers;
using CafeCritic.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace CafeCritic.Controllers;

public class UserController : Controller
{
    private readonly UserManager<User> _userManager;
    private readonly CafeDbContext _db;

    public UserController(UserManager<User> userManager, CafeDbContext db)
    {
        _userManager = userManager;
        _db = db;
    }

    // GET
    [HttpGet]
    [Authorize]
    [Display(Name = "AddReview")]
    public async Task<IActionResult> AddReviewAsync(string? reviw, int cafeId, Rating rating)
    {
        if (reviw == null)
        {
            return NotFound();
        }

        if (_db.Reviews.Any(r => r.CafeId == cafeId && r.UserId == _userManager.GetUserId(User)))
        {
            return BadRequest("Комментарий уже добавлен.");
        }

        var reviewDb = new Review
        {
            Description = reviw,
            DateOfCreat = DateTime.UtcNow,
            UserId = _userManager.GetUserId(User),
            CafeId = cafeId,
            Rating = (int)rating
        };
        await _db.Reviews.AddAsync(reviewDb);
        await _db.SaveChangesAsync();

        var answer = await _db.Reviews.Include(a => a.User)
            .Include(a => a.Cafe)
            .OrderBy(a => a.Id)
            .LastOrDefaultAsync();

        var viewModel = UserMapper.ReviewReviewViewModel(answer);
        return PartialView(viewModel);
    }
}