using Indotalent.ConfigBackEnd.Interfaces;
using Indotalent.ConfigFrontEnd.Common;
using Indotalent.Features.Profile.Avatar.Cqrs;
using Indotalent.Infrastructure.Authentication.Identity;
using Indotalent.Shared.Models;
using Microsoft.AspNetCore.Components;
using MudBlazor;
using RestSharp;

namespace Indotalent.Features.Profile.Avatar;

public class AvatarService : BaseService
{
    private readonly RestClient _client;

    public AvatarService(IHttpClientFactory clientFactory, NavigationManager nav, ISnackbar snackbar, ICurrentUserService currentUserService, TokenProvider tokenProvider)
            : base(clientFactory, nav, snackbar, currentUserService, tokenProvider)
    {
        _client = new RestClient(nav.BaseUri);
    }

    public async Task<ApiResponse<GetAvatarInfoResponse>?> GetAvatarInfoAsync(string userId)
    {
        var request = new RestRequest($"api/profile-avatar/info/{userId}", Method.Get);
        return await ExecuteWithResponseAsync<GetAvatarInfoResponse>(_client, request);
    }

    public async Task<ApiResponse<ChangeAvatarResponse>?> ChangeAvatarAsync(ChangeAvatarRequest data)
    {
        var request = new RestRequest("api/profile-avatar/change", Method.Post);
        request.AddJsonBody(data);
        return await ExecuteWithResponseAsync<ChangeAvatarResponse>(_client, request);
    }

    public async Task<byte[]?> GetAvatarBlobAsync(string fileName)
    {
        var request = new RestRequest($"api/profile-avatar/avatar-image/{fileName}", Method.Get);

        if (!string.IsNullOrEmpty(TokenProvider.Token))
        {
            request.AddHeader("Authorization", $"Bearer {TokenProvider.Token}");
        }

        if (!string.IsNullOrEmpty(CurrentUserService.UserId))
        {
            request.AddHeader("X-UserId", CurrentUserService.UserId);
        }

        var response = await _client.ExecuteAsync(request);

        return response.IsSuccessful ? response.RawBytes : null;
    }
}