using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using PSTW_CentralSystem.DBContext;

namespace PSTW_CentralSystem.Areas.Bookings.Controllers
{
    [Area("Bookings")]
    [Authorize] // require login for everything here
    public class BookingsController : Controller
    {
        private readonly CentralSystemContext _db;
        private readonly ILogger<BookingsController> _logger;

        public BookingsController(CentralSystemContext db, ILogger<BookingsController> logger)
        {
            _db = db;
            _logger = logger;
        }

        // ---------- helpers ----------
        private int? GetCurrentUserId()
        {
            var idStr = User?.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value;
            return int.TryParse(idStr, out var id) ? id : (int?)null;
        }

        // DB-backed manager check (NO Identity roles here)
        private Task<bool> IsManagerAsync()
        {
            var me = GetCurrentUserId();
            if (me is null) return Task.FromResult(false);
            return _db.BookingManager.AsNoTracking()
                     .AnyAsync(x => x.UserId == me.Value && x.IsActive);
        }

        private Task<bool> AnyManagersAsync()
            => _db.BookingManager.AsNoTracking().AnyAsync();

        private async Task<IActionResult?> RequireManagerOrForbidAsync()
        {
            if (await IsManagerAsync()) return null;
            return Forbid(); // or RedirectToAction(nameof(Index));
        }

        // ---------- pages ----------
        public IActionResult Index() => View();

        // Manager-only (rooms list/maintenance)
        public async Task<IActionResult> Room()
        {
            var gate = await RequireManagerOrForbidAsync();
            if (gate is not null) return gate;
            return View();
        }

        // Manager-only (create/edit room)
        public async Task<IActionResult> RoomsCreate()
        {
            var gate = await RequireManagerOrForbidAsync();
            if (gate is not null) return gate;
            return View();
        }

        // Everyone can view the calendar
        public IActionResult Calendar() => View();

        // Managers page:
        // - Bootstrap: if no managers exist yet, allow any authenticated user to seed.
        // - Otherwise: only managers.
        public async Task<IActionResult> Managers()
        {
            if (!await AnyManagersAsync())
            {
                ViewBag.Bootstrap = true; // optional UI hint
                return View();
            }

            var gate = await RequireManagerOrForbidAsync();
            if (gate is not null) return gate;

            ViewBag.Bootstrap = false;
            return View();
        }

        // Create/Edit booking (JS loads data by id)
        public IActionResult Create(int? id)
        {
            ViewBag.Id = id;
            return View();
        }
    }
}
