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

namespace AsadiTools.Pages.Blog;

public class BlogIndexModel(AppDbContext db) : PageModel
{
    public const int PageSize = 6;
    public List<BlogPost> Posts { get; private set; } = [];
    public int CurrentPage { get; private set; } = 1;
    public int TotalPages { get; private set; }
    public string? Tag { get; private set; }

    public async Task OnGetAsync(string? tag, int page = 1)
    {
        Tag = tag;

        var q = db.BlogPosts.Where(p => p.IsPublished);
        if (!string.IsNullOrEmpty(tag))
            q = q.Where(p => p.Tags != null && p.Tags.Contains(tag));

        var total = await q.CountAsync();
        TotalPages  = (int)Math.Ceiling(total / (double)PageSize);
        CurrentPage = Math.Clamp(page, 1, Math.Max(1, TotalPages));

        Posts = await q.OrderByDescending(p => p.PublishedAt)
                       .Skip((CurrentPage - 1) * PageSize)
                       .Take(PageSize)
                       .ToListAsync();

        ViewData["Title"]       = "بلاگ آساد ابزار — راهنما و مقالات تعمیر ابزار";
        ViewData["Description"] = "مقالات تخصصی تعمیر و نگهداری ابزار برقی. راهنمای خرید، نکات فنی و اخبار صنعت ابزار از آساد ابزار کرج.";
    }
}
