using AsadiTools.Data;
using AsadiTools.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;

namespace AsadiTools.Pages.Blog;

public class BlogPostModel(AppDbContext db) : PageModel
{
    public BlogPost? Post { get; private set; }
    public List<BlogPost> RelatedPosts { get; private set; } = [];

    public async Task<IActionResult> OnGetAsync(string slug)
    {
        Post = await db.BlogPosts
            .Where(p => p.IsPublished && p.Slug == slug)
            .FirstOrDefaultAsync();

        // Fallback: numeric slug = post ID
        if (Post is null && int.TryParse(slug, out var id))
            Post = await db.BlogPosts.Where(p => p.IsPublished && p.Id == id).FirstOrDefaultAsync();

        if (Post is null) return NotFound();

        // Related: same tag(s)
        var tags = Post.TagList;
        if (tags.Length > 0)
        {
            RelatedPosts = await db.BlogPosts
                .Where(p => p.IsPublished && p.Id != Post.Id && p.Tags != null)
                .ToListAsync();
            RelatedPosts = RelatedPosts
                .Where(p => p.TagList.Any(t => tags.Contains(t)))
                .OrderByDescending(p => p.PublishedAt)
                .Take(3)
                .ToList();
        }

        ViewData["Title"]       = Post.Title + " | آساد ابزار";
        ViewData["Description"] = Post.MetaDescription ?? Post.Excerpt ?? Post.Title;
        return Page();
    }
}
