using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authentication;
using System.Security.Claims;
using WarehouseAppSHIPS.Data;
using WarehouseAppSHIPS.Models;

namespace WarehouseAppSHIPS.Controllers
{
    public class AccountController : Controller
    {
        private readonly ApplicationDbContext _context;

        public AccountController(ApplicationDbContext context)
        {
            _context = context;
        }

        [HttpGet]
        public IActionResult Login()
        {
            // Fitur spesial: Jika database masih kosong sama sekali, buatkan 1 akun Admin Master otomatis
            if (!_context.AppUsers.Any())
            {
                _context.AppUsers.Add(new AppUser
                {
                    Username = "admin",
                    PasswordHash = "123",
                    FullName = "Rafli Fadilah",
                    Role = UserRole.MasterAdmin
                });
                _context.SaveChanges();
            }
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> Login(string username, string password)
        {
            // Cari user di database
            var user = _context.AppUsers.FirstOrDefault(u => u.Username == username && u.PasswordHash == password);

            if (user != null)
            {
                // Buat "KTP" digital untuk user yang login
                var claims = new List<Claim>
                {
                    new Claim(ClaimTypes.Name, user.Username),
                    new Claim("FullName", user.FullName),
                    new Claim(ClaimTypes.Role, user.Role.ToString()),
                    new Claim("UserId", user.Id.ToString())
                };

                var identity = new ClaimsIdentity(claims, "Cookies");
                var principal = new ClaimsPrincipal(identity);

                // Masuk!
                await HttpContext.SignInAsync("Cookies", principal);
                return RedirectToAction("Index", "Home");
            }

            ViewBag.Error = "Akses Ditolak! Username atau Password salah.";
            return View();
        }

        public async Task<IActionResult> Logout()
        {
            await HttpContext.SignOutAsync("Cookies");
            return RedirectToAction("Login");
        }
    }
}