using System.ComponentModel.DataAnnotations;
using CafeCritic.Context;
using CafeCritic.Mappers;
using CafeCritic.Models;
using CafeCritic.Services;
using CafeCritic.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;

namespace CafeCritic.Controllers;

public class CafeController : Controller
{
    private readonly CafeDbContext _db;

    private readonly UserManager<User> _userManager;

    public CafeController(CafeDbContext db, UserManager<User> userManager)
    {
        _db = db;
        _userManager = userManager;
    }
    
    [HttpGet]
    public IActionResult Index()
    {
        List<Cafe> models = _db.Cafes.ToList();
        
        return View(models);
    }

    [HttpGet]
    [Authorize]
    public IActionResult AddCafe()
    {
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    [Display(Name="AddCafe")]
    public async Task<IActionResult> AddCafeAsync(AddCafeViewModel model)
    {
        if (!ModelState.IsValid) return View(model);
        
        var image = await FileUpload.Upload(model.Title, model.Image);
        var restaurant = CafeMapper.AddCafeCafe(model, image);
        

        await _db.Cafes.AddAsync(restaurant);
        await _db.SaveChangesAsync();

        return RedirectToAction("Index", "Cafe");
    }

    public IActionResult Details(int id)
    {
        var cafe = _db.Cafes.FirstOrDefault(c => c.Id == id);
        if (cafe is null)
        {
            return NotFound();
        }

        return View(cafe);
    }
}