using Hangfire;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.RazorPages;
using QuantEngine.Application.Interfaces;
using QuantEngine.Web.Services;

namespace QuantEngine.Web.Pages.Admin.Collection;

[Authorize(AuthenticationSchemes = AdminAuthDefaults.Scheme)]
public class StartModel : PageModel
{
    private readonly IBackgroundJobClient _jobClient;
    private readonly IConfiguration _configuration;
    private readonly ILogger<StartModel> _logger;

    public string? RunId { get; private set; }
    public string? ErrorMessage { get; private set; }

    public StartModel(
        IBackgroundJobClient jobClient,
        IConfiguration configuration,
        ILogger<StartModel> logger)
    {
        _jobClient = jobClient;
        _configuration = configuration;
        _logger = logger;
    }

    public void OnGet()
    {
        try
        {
            RunId = $"admin-{DateTime.Now:yyyyMMdd-HHmmss}";
            var accountMode = _configuration["Kis:AccountMode"] ?? "mock";
            var tickers = new[] { "005930", "000660", "051910", "005380", "010140", "005490" }.ToList();

            _jobClient.Enqueue<ICollectionOrchestrator>(orchestrator =>
                orchestrator.RunCollectionAsync(RunId!, accountMode, tickers));

            _logger.LogInformation("Collection run {RunId} enqueued from admin page", RunId);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to enqueue collection run from admin page");
            ErrorMessage = "수집 작업을 등록하지 못했습니다. Hangfire 상태와 서버 로그를 확인하세요.";
        }
    }
}
