using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using SkyArtShop.Models;
using SkyArtShop.Services;

namespace SkyArtShop.Controllers;

public class BlogController : Controller
{
	private readonly PostgreSQLService _pgService;

	private readonly string _blogCollection = "BlogPosts";

	public BlogController(PostgreSQLService pgService)
	{
		_pgService = pgService;
	}

	public async Task<IActionResult> Index()
	{
		List<BlogPost> model = (from p in await _pgService.GetAllAsync<BlogPost>(_blogCollection)
			where p.IsPublished
			orderby p.PublishedDate descending
			select p).ToList();
		return View(model);
	}

	public async Task<IActionResult> Post(string slug)
	{
		BlogPost blogPost = (await _pgService.GetAllAsync<BlogPost>(_blogCollection)).FirstOrDefault((BlogPost p) => p.Slug == slug && p.IsPublished);
		if (blogPost == null)
		{
			return NotFound();
		}
		return View(blogPost);
	}
}
