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

namespace TaxBaik.Web.Pages.Portal;

public class RegisterModel : PageModel
{
    private readonly PortalUserService _portalUserService;
    private readonly ClientService _clientService;

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

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

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

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

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

    public RegisterModel(PortalUserService portalUserService, ClientService clientService)
    {
        _portalUserService = portalUserService;
        _clientService = clientService;
    }

    public void OnGet()
    {
    }

    public async Task<IActionResult> OnPostAsync()
    {
        if (string.IsNullOrWhiteSpace(Name) || string.IsNullOrWhiteSpace(Email))
        {
            ErrorMessage = "이름과 이메일을 입력하세요.";
            return Page();
        }

        if (string.IsNullOrWhiteSpace(Password) || Password.Length < 8)
        {
            ErrorMessage = "비밀번호는 8자 이상이어야 합니다.";
            return Page();
        }

        var existing = await _portalUserService.GetByEmailAsync(Email);
        if (existing is not null)
        {
            ErrorMessage = "이미 등록된 이메일입니다.";
            return Page();
        }

        int? clientId = null;
        var linkedClient = await _clientService.GetByEmailAsync(Email);
        if (linkedClient is null && !string.IsNullOrWhiteSpace(Phone))
            linkedClient = await _clientService.GetByPhoneAsync(Phone);
        if (linkedClient is not null)
            clientId = linkedClient.Id;

        await _portalUserService.RegisterLocalAsync(
            Name,
            Email,
            Phone,
            PortalAuthService.HashPassword(Password),
            clientId: clientId);

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