using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using NewsAnalysis.Data;

namespace NewsAnalysis.Controllers;

public class NewsController : Controller
{
    private readonly ApplicationDbContext _db;

    public NewsController(ApplicationDbContext db)
    {
        _db = db;
    }

    public async Task<IActionResult> Index(int page = 1, string? sentiment = null)
    {
        const int pageSize = 12;

        var query = _db.News.AsQueryable();

        if (!string.IsNullOrEmpty(sentiment) && sentiment != "all")
            query = query.Where(n => n.Sentiment == sentiment);

        var totalCount  = await query.CountAsync();
        var news        = await query
            .OrderByDescending(n => n.Id)
            .Skip((page - 1) * pageSize)
            .Take(pageSize)
            .ToListAsync();

        // Grafik için istatistikler (filtreden bağımsız, tüm haberler)
        var stats = await _db.News
            .Where(n => n.Sentiment != null)
            .GroupBy(n => n.Sentiment)
            .Select(g => new { Sentiment = g.Key, Count = g.Count() })
            .ToListAsync();

        ViewBag.Positive       = stats.FirstOrDefault(s => s.Sentiment == "positive")?.Count ?? 0;
        ViewBag.Negative       = stats.FirstOrDefault(s => s.Sentiment == "negative")?.Count ?? 0;
        ViewBag.Neutral        = stats.FirstOrDefault(s => s.Sentiment == "neutral")?.Count ?? 0;
        ViewBag.Unanalyzed     = await _db.News.CountAsync(n => n.Sentiment == null);

        ViewBag.CurrentPage    = page;
        ViewBag.TotalPages     = (int)Math.Ceiling(totalCount / (double)pageSize);
        ViewBag.TotalCount     = totalCount;
        ViewBag.ActiveSentiment = sentiment ?? "all";

        return View(news);
    }
}
