using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using SkyArtShop.Models;
using SkyArtShop.Services;

namespace SkyArtShop.Controllers
{
    [Route("admin/blog")]
    [Authorize(Roles="Admin")]
    public class AdminBlogController : Controller
    {
        private readonly MongoDBService _mongoService;
        private readonly SlugService _slugService;
        private readonly string _blogCollection = "BlogPosts";

        public AdminBlogController(MongoDBService mongoService, SlugService slugService)
        {
            _mongoService = mongoService;
            _slugService = slugService;
        }

        [HttpGet("")]
        public async Task<IActionResult> Index()
        {
            var posts = await _mongoService.GetAllAsync<BlogPost>(_blogCollection);
            return View(posts.OrderByDescending(p => p.CreatedAt).ToList());
        }

        [HttpGet("create")]
        public IActionResult Create() => View(new BlogPost());

        [HttpPost("create")]
        public async Task<IActionResult> Create(BlogPost post)
        {
            if (!ModelState.IsValid)
            {
                return View(post);
            }

            post.CreatedAt = DateTime.UtcNow;
            post.UpdatedAt = DateTime.UtcNow;
            post.PublishedDate = DateTime.UtcNow;
            post.Slug = _slugService.GenerateSlug(post.Title);
            await _mongoService.InsertAsync(_blogCollection, post);
            TempData["SuccessMessage"] = "Blog post created successfully!";
            return RedirectToAction("Index");
        }

        [HttpGet("edit/{id}")]
        public async Task<IActionResult> Edit(string id)
        {
            var post = await _mongoService.GetByIdAsync<BlogPost>(_blogCollection, id);
            if (post == null) return NotFound();
            return View(post);
        }

        [HttpPost("edit/{id}")]
        public async Task<IActionResult> Edit(string id, BlogPost post)
        {
            if (!ModelState.IsValid)
            {
                return View(post);
            }

            post.Id = id;
            post.UpdatedAt = DateTime.UtcNow;
            post.Slug = _slugService.GenerateSlug(post.Title);
            await _mongoService.UpdateAsync(_blogCollection, id, post);
            TempData["SuccessMessage"] = "Blog post updated successfully!";
            return RedirectToAction("Index");
        }

        [HttpPost("delete/{id}")]
        public async Task<IActionResult> Delete(string id)
        {
            await _mongoService.DeleteAsync<BlogPost>(_blogCollection, id);
            TempData["SuccessMessage"] = "Blog post deleted successfully!";
            return RedirectToAction("Index");
        }

        private string GenerateSlug(string text)
        {
            return _slugService.GenerateSlug(text);
        }
    }
}
