using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using SkyArtShop.Models;
using SkyArtShop.Services;

namespace SkyArtShop.Controllers
{
    [Route("admin/settings")]
    [Authorize(Roles="Admin")]
    public class AdminSettingsController : Controller
    {
        private readonly MongoDBService _mongoService;
        private readonly string _settingsCollection = "SiteSettings";

        public AdminSettingsController(MongoDBService mongoService)
        {
            _mongoService = mongoService;
        }

        [HttpGet("")]
        public async Task<IActionResult> Index()
        {
            var settingsList = await _mongoService.GetAllAsync<SiteSettings>(_settingsCollection);
            var settings = settingsList.FirstOrDefault();
            if (settings == null)
            {
                settings = new SiteSettings();
                await _mongoService.InsertAsync(_settingsCollection, settings);
            }
            return View(settings);
        }

        [HttpPost("update")]
        public async Task<IActionResult> Update(SiteSettings settings)
        {
            if (!ModelState.IsValid)
            {
                return View("Index", settings);
            }

            settings.UpdatedAt = DateTime.UtcNow;
            if (!string.IsNullOrEmpty(settings.Id))
            {
                await _mongoService.UpdateAsync(_settingsCollection, settings.Id, settings);
            }
            else
            {
                await _mongoService.InsertAsync(_settingsCollection, settings);
            }
            TempData["SuccessMessage"] = "Site settings updated successfully!";
            return RedirectToAction("Index");
        }
    }
}
