using System.Security.Claims;
using MediatR;
using Web.Api.Common;
using Web.Api.Extensions;

namespace Web.Api.Endpoints.Studio.Settings;

/// <summary>채널 연결 — OAuth 코드 교환 및 채널 저장</summary>
internal sealed class ConnectYouTube : IEndpoint
{
    public void MapEndpoint(IEndpointRouteBuilder app)
    {
        app.MapPost("api/studio/youtube-connect", async (
            ClaimsPrincipal user,
            Request request,
            ISender sender,
            CancellationToken ct
        ) => {
            var memberID = user.GetRequiredMemberID();

            try
            {
                await sender.Send(new Application.Features.Api.Studio.ConnectYouTube.Command(memberID, request.Code, request.RedirectUri), ct);

                return ApiResponse.Ok();
            }
            catch (InvalidOperationException ex)
            {
                return Results.Problem(ex.Message, statusCode: 400);
            }
        })
        .WithTags("Studio")
        .RequireAuthorization();
    }

    private sealed record Request(string Code, string RedirectUri);
}