using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SkyArtShop.Models;
using SkyArtShop.Services;

namespace SkyArtShop.Controllers;

[Route("admin/settings")]
[Authorize(Roles = "Admin,MasterAdmin")]
public class AdminSettingsController : Controller
{
	private readonly PostgreSQLService _pgService;

	private readonly string _settingsCollection = "SiteSettings";

	public AdminSettingsController(PostgreSQLService pgService)
	{
		_pgService = pgService;
	}

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

	[HttpPost("update")]
	public async Task<IActionResult> Update(SiteSettings settings)
	{
		if (!base.ModelState.IsValid)
		{
			return View("Index", settings);
		}
		settings.UpdatedAt = DateTime.UtcNow;
		if (string.IsNullOrEmpty(settings.Id))
		{
			await _pgService.InsertAsync(_settingsCollection, settings);
		}
		else
		{
			await _pgService.UpdateAsync(_settingsCollection, settings.Id, settings);
		}
		base.TempData["SuccessMessage"] = "Site settings updated successfully!";
		return RedirectToAction("Index");
	}
}
