using Application.Abstractions.Data;
using Application.Abstractions.Messaging;
using Application.Abstractions.YouTube;
using Microsoft.EntityFrameworkCore;
using SharedKernel.Results;

namespace Application.Features.Api.Studio.GetYouTubeConnectUrl;

internal sealed class Handler(IAppDbContext db, IGoogleOAuthService oauthService) : IQueryHandler<Query, Result<string>>
{
    public async Task<Result<string>> Handle(Query request, CancellationToken ct)
    {
        var config = await db.Config.AsNoTracking().OrderByDescending(x => x.ID).FirstOrDefaultAsync(ct);

        if (config is null || string.IsNullOrEmpty(config.External.GoogleClientId))
        {
            return Result.Failure<string>(Error.Problem("Studio.ConfigMissing", "Google OAuth 설정이 없습니다."));
        }

        var state = Guid.NewGuid().ToString("N");
        var baseUrl = oauthService.GetAuthorizationUrl(state, request.RedirectUri, GoogleOAuthScopes.Default);
        var fullUrl = $"{baseUrl}&client_id={Uri.EscapeDataString(config.External.GoogleClientId)}";

        return Result.Success(fullUrl);
    }
}