using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using OpenWarehouse.auth.lib.Model.Service;
using OpenWarehouse.warehouse.api.Common.DefaultServiceAccountAndRole;
using OpenWarehouse.warehouse.api.Common.ServiceClaims;
using OpenWarehouse.warehouse.api.Model.Tool;

namespace OpenWarehouse.warehouse.api.Controller;

[ApiController]
[Route("[action]")]
public class Tools(
    IConfiguration configuration,
    DefaultIdentify defaultIdentify,
    IServiceClaimsManager serviceClaimsManager) : ControllerBase
{
    [HttpGet]
    public Task<ActionResult<PingModel>> Ping()
    {
        return Task.FromResult<ActionResult<PingModel>>(Ok(new PingModel()));
    }

    [HttpPost]
    [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
    public async Task<ActionResult<InitialziationResultModel>> InitServiceConnectionWithAuth()
    {
        Request.Headers.TryGetValue("Authorization", out var token);


        var result = await defaultIdentify.SeedAsync(token.ToString());

        var testResult = false;

        if (result.IsSuccess || result.UserAllereadyExist)
        {
            testResult = await defaultIdentify.TestAuth(result.ServiceToken ??
                                                        throw new ArgumentNullException(
                                                            $"Service {result.ServiceName} token is null"));
            if (testResult)
            {
                await serviceClaimsManager.UpdateClaim(ServiceClaim.ServiceAcoountToken, result.ServiceToken);
                await serviceClaimsManager.UpdateClaim(ServiceClaim.ServiceAcoountUsername, result.ServiceUsername ??
                    throw new ArgumentNullException(
                        $"Service {result.ServiceName} username is null"));
            }
        }

        return Ok(new InitialziationResultModel()
        {
            Success = result.IsSuccess,
            IsAlreadyInitialized = result.UserAllereadyExist,
            ServiceAccountName = result.ServiceName,
            TestAuthSuccess = testResult
        });

    }
}