using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using PowderCoating.Application.Interfaces;
using PowderCoating.Core.Interfaces;
using PowderCoating.Shared.Constants;

namespace PowderCoating.Web.Controllers;

/// <summary>
/// Allows company admins logged into the DEMO company to reset demo data without
/// switching to a SuperAdmin account. The CompanyCode guard ensures this action
/// cannot affect any real tenant even if someone crafts a direct POST.
/// </summary>
[Authorize(Policy = AppConstants.Policies.CompanyAdminOnly)]
public class DemoController : Controller
{
    private readonly ISeedDataService _seedDataService;
    private readonly ITenantContext _tenantContext;
    private readonly IUnitOfWork _unitOfWork;
    private readonly ILogger<DemoController> _logger;

    public DemoController(
        ISeedDataService seedDataService,
        ITenantContext tenantContext,
        IUnitOfWork unitOfWork,
        ILogger<DemoController> logger)
    {
        _seedDataService = seedDataService;
        _tenantContext   = tenantContext;
        _unitOfWork      = unitOfWork;
        _logger          = logger;
    }

    /// <summary>
    /// Resets the demo company's seed data and redirects back to the dashboard.
    /// Fails fast if the current company is not the DEMO company.
    /// </summary>
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> ResetDemoData()
    {
        var companyId = _tenantContext.GetCurrentCompanyId();
        if (companyId == null)
        {
            TempData["ErrorMessage"] = "Unable to determine current company.";
            return RedirectToAction("Index", "CompanySettings");
        }

        // Safety gate: only the DEMO company can use this action
        var company = await _unitOfWork.Companies.GetByIdAsync(companyId.Value);
        if (company == null || company.CompanyCode != "DEMO")
        {
            TempData["ErrorMessage"] = "Demo reset is only available for the DEMO company.";
            return RedirectToAction("Index", "CompanySettings");
        }

        try
        {
            var removeOptions = new RemoveSeedDataOptions
            {
                Customers      = true,
                InventoryItems = true,
                Equipment      = true,
                Catalog        = true,
                Bills          = true,
                Expenses       = true,
                Workers        = false,
                Vendors        = true,
                NamedOvens     = true,
                Appointments   = true,
                ForceRemoveAll = true,
            };

            var removeResult = await _seedDataService.RemoveSeedDataAsync(companyId.Value, removeOptions);
            if (!removeResult.Success)
            {
                TempData["ErrorMessage"] = $"Demo reset failed during wipe: {removeResult.Message}";
                return RedirectToAction("Index", "CompanySettings");
            }

            var seedResult = await _seedDataService.SeedCompanyDataAsync(companyId.Value);

            TempData["SuccessMessage"] = $"Demo data reset complete &mdash; {seedResult.ItemsSeeded} records refreshed with today&rsquo;s dates.";

            if (seedResult.Warnings.Any())
                TempData["WarningMessage"] = $"{seedResult.Warnings.Count} item(s) skipped during reseed (check Platform &rsaquo; Seed Data for details).";
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error resetting demo data for company {CompanyId}", companyId);
            TempData["ErrorMessage"] = $"Demo reset encountered an error: {ex.Message}";
        }

        return RedirectToAction("Index", "CompanySettings");
    }
}
