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

namespace EonaCat.LogStack.Status.Pages.Admin;

// 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 AlertRulesModel : PageModel
{
    private readonly DatabaseContext _database;
    public AlertRulesModel(DatabaseContext database) => _database = database;

    public List<AlertRule> Rules { get; set; } = new();
    public List<Monitor> Monitors { get; set; } = new();
    public string? Message { get; set; }

    [BindProperty] public AlertRule NewRule { get; set; } = new();

    public async Task<IActionResult> OnGetAsync()
    {
        if (HttpContext.Session.GetString("IsAdmin") != "true")
        {
            return RedirectToPage("/Admin/Login");
        }

        Rules = await _database.AlertRules
            .Include(r => r.Monitor)
            .OrderBy(r => r.MonitorId)
            .ToListAsync();

        Monitors = await _database.Monitors.Where(m => m.IsActive).OrderBy(m => m.Name).ToListAsync();
        return Page();
    }

    public async Task<IActionResult> OnPostSaveAsync()
    {
        if (HttpContext.Session.GetString("IsAdmin") != "true")
        {
            return RedirectToPage("/Admin/Login");
        }

        NewRule.IsEnabled = true;
        _database.AlertRules.Add(NewRule);
        await _database.SaveChangesAsync();
        Message = "Alert rule saved.";
        return await OnGetAsync();
    }

    public async Task<IActionResult> OnPostToggleAsync(int id)
    {
        if (HttpContext.Session.GetString("IsAdmin") != "true")
        {
            return RedirectToPage("/Admin/Login");
        }

        var rule = await _database.AlertRules.FindAsync(id);
        if (rule != null)
        {
            rule.IsEnabled = !rule.IsEnabled;
            await _database.SaveChangesAsync();
        }

        Message = "Rule updated.";
        return await OnGetAsync();
    }

    public async Task<IActionResult> OnPostDeleteAsync(int id)
    {
        if (HttpContext.Session.GetString("IsAdmin") != "true")
        {
            return RedirectToPage("/Admin/Login");
        }

        var rule = await _database.AlertRules.FindAsync(id);
        if (rule != null)
        {
            _database.AlertRules.Remove(rule);
            await _database.SaveChangesAsync();
        }

        Message = "Rule deleted.";
        return await OnGetAsync();
    }
}
