using Fengling.AuthService.Data;
using Fengling.AuthService.Models;
using Fengling.AuthService.ViewModels;
using Fengling.Platform.Domain.AggregatesModel.TenantAggregate;
using Fengling.Platform.Infrastructure;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace Fengling.AuthService.Controllers;

[Route("account")]
public class AccountController(
    UserManager<ApplicationUser> userManager,
    SignInManager<ApplicationUser> signInManager,
    ApplicationDbContext dbContext,
    ILogger<AccountController> logger,
    PlatformDbContext platformDbContext)
    : Controller
{
    [HttpGet("login")]
    public IActionResult Login(string returnUrl = "/")
    {
        return View(new LoginInputModel { ReturnUrl = returnUrl });
    }

    [HttpPost("login")]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Login(LoginInputModel model)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }

        var user = await userManager.FindByNameAsync(model.Username);
        if (user == null || user.IsDeleted)
        {
            ModelState.AddModelError(string.Empty, "用户名或密码错误");
            return View(model);
        }

        var result = await signInManager.PasswordSignInAsync(user, model.Password, model.RememberMe, true);
        if (!result.Succeeded)
        {
            if (result.IsLockedOut)
            {
                ModelState.AddModelError(string.Empty, "账号已被锁定");
            }
            else
            {
                ModelState.AddModelError(string.Empty, "用户名或密码错误");
            }
            return View(model);
        }

        return LocalRedirect(model.ReturnUrl);
    }

    [HttpGet("register")]
    public IActionResult Register(string returnUrl = "/")
    {
        return View(new RegisterViewModel { ReturnUrl = returnUrl });
    }

    [HttpPost("register")]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Register(RegisterViewModel model)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }

        var tenant = await platformDbContext.Tenants
            .FirstOrDefaultAsync(t => t.TenantCode == model.TenantCode);

        if (tenant == null)
        {
            ModelState.AddModelError(string.Empty, $"系统配置错误：未找到租户{model.TenantCode}");
            return View(model);
        }

        var user = new ApplicationUser
        {
            UserName = model.Username,
            Email = model.Email,
            NormalizedUserName = model.Username.ToUpper(),
            NormalizedEmail = model.Email.ToUpper(),
            TenantInfo = new TenantInfo(tenant)
        };

        var result = await userManager.CreateAsync(user, model.Password);
        if (!result.Succeeded)
        {
            foreach (var error in result.Errors)
            {
                ModelState.AddModelError(string.Empty, error.Description);
            }
            return View(model);
        }

        await signInManager.SignInAsync(user, isPersistent: false);
        return LocalRedirect(model.ReturnUrl);
    }

    [HttpGet("profile")]
    [HttpGet("settings")]
    [HttpGet("～/connect/logout")]
    public IActionResult NotImplemented()
    {
        return RedirectToAction("Index", "Dashboard");
    }

    [HttpPost("～/connect/logout")]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> LogoutPost()
    {
        await signInManager.SignOutAsync();
        return Redirect("/");
    }
}
