using Microsoft.AspNetCore.Mvc;
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.Admin;

public class CertificatesModel : PageModel
{
    // 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.

    private readonly DatabaseContext _db;
    private readonly MonitoringService _monSvc;
    public CertificatesModel(DatabaseContext db, MonitoringService monSvc) { _db = db; _monSvc = monSvc; }

    public List<CertificateEntry> Certificates { get; set; } = new();
    [BindProperty] public CertificateEntry EditCert { get; set; } = new();
    public string? Message { get; set; }

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

        Certificates = await _db.Certificates.OrderBy(c => c.ExpiresAt).ToListAsync();
        Message = msg;
        return Page();
    }

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

        if (EditCert.Id == 0)
        {
            _db.Certificates.Add(EditCert);
        }
        else
        {
            var e = await _db.Certificates.FindAsync(EditCert.Id);
            if (e != null)
            {
                e.Name = EditCert.Name;
                e.Domain = EditCert.Domain;
                e.Port = EditCert.Port;
                e.IsPublic = EditCert.IsPublic;
                e.AlertOnExpiry = EditCert.AlertOnExpiry;
                e.AlertDaysBeforeExpiry = EditCert.AlertDaysBeforeExpiry;
            }
        }
        await _db.SaveChangesAsync();
        return RedirectToPage(new { msg = "Certificate saved." });
    }

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

        var c = await _db.Certificates.FindAsync(id);
        if (c != null) { _db.Certificates.Remove(c); await _db.SaveChangesAsync(); }
        return RedirectToPage(new { msg = "Certificate deleted." });
    }

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

        var c = await _db.Certificates.FindAsync(id);
        if (c != null)
        {
            await _monSvc.CheckCertificateAsync(c);
        }

        return RedirectToPage(new { msg = "Certificate checked." });
    }
}
