using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using TaxBaik.Web.Services;

namespace TaxBaik.Web.Pages.Portal;

public class LoginModel : PageModel
{
    private readonly PortalAuthService _portalAuthService;

    [BindProperty]
    public string Email { get; set; } = "";

    [BindProperty]
    public string Password { get; set; } = "";

    [BindProperty]
    public string? ErrorMessage { get; set; }

    public LoginModel(PortalAuthService portalAuthService)
    {
        _portalAuthService = portalAuthService;
    }

    public void OnGet()
    {
    }

    public async Task<IActionResult> OnPostAsync()
    {
        if (string.IsNullOrWhiteSpace(Email) || string.IsNullOrWhiteSpace(Password))
        {
            ErrorMessage = "이메일과 비밀번호를 입력하세요.";
            return Page();
        }

        var signedIn = await _portalAuthService.SignInAsync(Email, Password);
        if (!signedIn)
        {
            ErrorMessage = "로그인 정보를 확인할 수 없습니다.";
            return Page();
        }

        return RedirectToPage("/Portal/Index");
    }

    public IActionResult OnPostGoogle() => Challenge(BuildProps("google"), PortalOAuthDefaults.GoogleScheme);

    public IActionResult OnPostNaver() => Challenge(BuildProps("naver"), PortalOAuthDefaults.NaverScheme);

    public IActionResult OnPostKakao() => Challenge(BuildProps("kakao"), PortalOAuthDefaults.KakaoScheme);

    private static AuthenticationProperties BuildProps(string provider) =>
        new() { RedirectUri = $"/portal/external-callback?provider={provider}" };
}
