// AccountController.cs
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Facebook;
using Microsoft.AspNetCore.Mvc;
using Postall.Domain.Services.Contracts;
using System.Security.Claims;

namespace Postall.Controllers
{
    public class OtherLoginsController : Controller
    {
        private readonly IFacebookServices _facebookServices;

        public OtherLoginsController(IFacebookServices facebookServices)
        {
            this._facebookServices = facebookServices;
        }
        [HttpGet]
        public IActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public IActionResult FacebookLogin()
        {
            var properties = new AuthenticationProperties { RedirectUri = Url.Action("FacebookResponse") };
            return Challenge(properties, FacebookDefaults.AuthenticationScheme);
        }

        [HttpGet]
        public async Task<IActionResult> FacebookResponse()
        {
            var result = await HttpContext.AuthenticateAsync(FacebookDefaults.AuthenticationScheme);
            if (!result.Succeeded) return RedirectToAction("Login");

            var accessToken = result.Properties.GetTokenValue("access_token");
            var longLivedToken = await _facebookServices.GetLongLivedToken(accessToken);

            var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
            await _facebookServices.SaveFacebookToken(userId, longLivedToken);

            return RedirectToAction("Index", "Home");
        }

        [HttpPost]
        public IActionResult Logout()
        {
            return SignOut("Cookies", FacebookDefaults.AuthenticationScheme);
        }
    }
}