using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.RazorPages;
using QuantEngine.Web.Services;

namespace QuantEngine.Web.Pages.Admin.Operations;

[Authorize(AuthenticationSchemes = AdminAuthDefaults.Scheme)]
public class IndexModel : PageModel
{
    private readonly ILogger<IndexModel> _logger;

    public List<ScheduledJobInfo>? ScheduledJobs { get; set; }
    public List<JobExecutionInfo>? RecentExecutions { get; set; }
    public int TotalJobsCount { get; set; }
    public int ActiveJobsCount { get; set; }
    public int InactiveJobsCount { get; set; }
    public int PendingJobsCount { get; set; }
    public bool IsJobProcessorRunning { get; set; }
    public DateTime? LastRefreshTime { get; set; }
    public string? StatusMessage { get; set; }

    public IndexModel(ILogger<IndexModel> logger)
    {
        _logger = logger;
    }

    public async Task OnGetAsync()
    {
        await LoadOperationsData();
    }

    private async Task LoadOperationsData()
    {
        try
        {
            LastRefreshTime = DateTime.UtcNow;

            ScheduledJobs = new List<ScheduledJobInfo>
            {
                new("KIS 데이터 수집", "매일 09:00", DateTime.UtcNow.AddHours(1), true),
                new("포트폴리오 스냅샷", "매일 17:00", DateTime.UtcNow.AddHours(8), true),
                new("일일 리포트 생성", "매일 08:00", DateTime.UtcNow.AddHours(-1), true),
                new("데이터 정리", "주 1회 (월)", DateTime.UtcNow.AddDays(5), true)
            };

            RecentExecutions = new List<JobExecutionInfo>
            {
                new("포트폴리오 스냅샷", DateTime.UtcNow.AddHours(-2), DateTime.UtcNow.AddHours(-2).AddSeconds(45), true),
                new("KIS 데이터 수집", DateTime.UtcNow.AddHours(-4), DateTime.UtcNow.AddHours(-4).AddSeconds(120), true),
                new("일일 리포트 생성", DateTime.UtcNow.AddHours(-6), DateTime.UtcNow.AddHours(-6).AddSeconds(30), true),
                new("KIS 데이터 수집", DateTime.UtcNow.AddHours(-24), DateTime.UtcNow.AddHours(-24).AddSeconds(110), true)
            };

            TotalJobsCount = ScheduledJobs.Count;
            ActiveJobsCount = ScheduledJobs.Count(j => j.IsEnabled);
            InactiveJobsCount = TotalJobsCount - ActiveJobsCount;
            PendingJobsCount = 0;
            IsJobProcessorRunning = true;
            StatusMessage = "모든 작업이 정상적으로 실행 중입니다.";

            _logger.LogInformation("Operations data loaded successfully");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to load operations data");
            ScheduledJobs = [];
            RecentExecutions = [];
            StatusMessage = "데이터 로딩 중 오류가 발생했습니다.";
        }
    }
}

public record ScheduledJobInfo(string JobName, string Schedule, DateTime? NextRun, bool IsEnabled);
public record JobExecutionInfo(string JobName, DateTime StartedAt, DateTime? CompletedAt, bool IsSuccess);
