using CMSMicroservice.Infrastructure.BackgroundJobs;
using Hangfire;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace CMSMicroservice.WebApi.Controllers;

/// <summary>
/// Admin endpoints for manual job triggers and system management
/// </summary>
[ApiController]
[Route("api/[controller]")]
//[Authorize(Roles = "Admin")] // TODO: Enable when authentication is configured
public class AdminController : ControllerBase
{
    private readonly IBackgroundJobClient _backgroundJobClient;
    private readonly IRecurringJobManager _recurringJobManager;
    private readonly ILogger<AdminController> _logger;

    public AdminController(
        IBackgroundJobClient backgroundJobClient,
        IRecurringJobManager recurringJobManager,
        ILogger<AdminController> logger)
    {
        _backgroundJobClient = backgroundJobClient;
        _recurringJobManager = recurringJobManager;
        _logger = logger;
    }

    /// <summary>
    /// Manually trigger weekly commission calculation for a specific week
    /// </summary>
    /// <param name="weekNumber">Week number in YYYY-Www format (e.g., 2025-W48). If null, uses previous week.</param>
    /// <returns>Job ID for tracking</returns>
    [HttpPost("trigger-weekly-calculation")]
    public IActionResult TriggerWeeklyCalculation([FromQuery] long? weekDefinitionId = null)
    {
        _logger.LogInformation("🔧 Manual trigger requested by admin for WeekDefinitionId: {WeekDefinitionId}", weekDefinitionId?.ToString() ?? "previous");

        // Enqueue immediate job execution with specified week
        var jobId = _backgroundJobClient.Enqueue<WeeklyCommissionJob>(
            job => job.ExecuteAsync(weekDefinitionId, CancellationToken.None));

        _logger.LogInformation("✅ Job enqueued with ID: {JobId}", jobId);

        return Ok(new
        {
            success = true,
            jobId = jobId,
            message = "Weekly calculation job enqueued successfully",
            dashboardUrl = $"/hangfire/jobs/details/{jobId}"
        });
    }

    /// <summary>
    /// Trigger recurring job immediately (without waiting for schedule)
    /// </summary>
    [HttpPost("trigger-recurring-job-now")]
    public IActionResult TriggerRecurringJobNow()
    {
        _logger.LogInformation("🔧 Triggering recurring job immediately");

        _recurringJobManager.Trigger("weekly-commission-calculation");

        return Ok(new
        {
            success = true,
            message = "Recurring job triggered successfully"
        });
    }

    /// <summary>
    /// Get status of recurring jobs
    /// </summary>
    [HttpGet("recurring-jobs-status")]
    public IActionResult GetRecurringJobsStatus()
    {
        return Ok(new
        {
            jobs = new[]
            {
                new
                {
                    id = "weekly-commission-calculation",
                    cron = "5 0 * * 0",
                    description = "Weekly Commission Calculation - Every Sunday at 00:05 UTC",
                    dashboardUrl = "/hangfire/recurring"
                }
            }
        });
    }
}
