using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using EonaCat.LogStack.Status.Data;
using EonaCat.LogStack.Status.Models;
using EonaCat.LogStack.Status.Services;

namespace EonaCat.LogStack.Status.Pages;

// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.

public class IncidentsModel : PageModel
{
    private readonly DatabaseContext _db;
    private readonly AuthenticationService _authSvc;

    public IncidentsModel(DatabaseContext db, AuthenticationService authSvc)
    {
        _db = db;
        _authSvc = authSvc;
    }

    public List<Incident> Incidents { get; set; } = new();

    public async Task OnGetAsync()
    {
        var isAdmin = HttpContext.Session.GetString("IsAdmin") == "true";
        var showIncidents = (await _authSvc.GetSettingAsync("ShowIncidentsPublicly", "true")) == "true";

        if (!isAdmin && !showIncidents)
        {
            Incidents = new List<Incident>();
            return;
        }

        var query = _db.Incidents
            .Include(i => i.Updates)
            .Include(i => i.Monitor)
            .AsQueryable();

        if (!isAdmin)
        {
            query = query.Where(i => i.IsPublic);
        }

        Incidents = await query.OrderByDescending(i => i.CreatedAt).ToListAsync();
    }
}
