using System.Text.RegularExpressions;

namespace Application.Abstractions.YouTube;

/// <summary>
/// YouTube URL에서 채널 ID, 핸들, 비디오 ID를 추출하는 유틸리티
/// </summary>
public static partial class YouTubeUrlHelper
{
    /// <summary>
    /// YouTube URL에서 Channel ID 추출
    /// 지원 형식:
    /// - https://www.youtube.com/channel/UCxxxxxxxxx
    /// - https://www.youtube.com/@handle
    /// - https://youtube.com/c/CustomName
    /// </summary>
    public static (string? channelId, string? handle) ExtractChannelInfo(string url)
    {
        if (string.IsNullOrWhiteSpace(url))
        {
            return (null, null);
        }

        // /channel/UCxxxxx 형식
        var channelMatch = ChannelIdRegex().Match(url);
        if (channelMatch.Success)
        {
            return (channelMatch.Groups[1].Value, null);
        }

        // /@handle 형식
        var handleMatch = HandleRegex().Match(url);
        if (handleMatch.Success)
        {
            return (null, handleMatch.Groups[1].Value);
        }

        // /c/CustomName 형식 → 핸들로 처리
        var customMatch = CustomUrlRegex().Match(url);
        if (customMatch.Success)
        {
            return (null, customMatch.Groups[1].Value);
        }

        return (null, null);
    }

    /// <summary>
    /// YouTube URL에서 Video ID 추출
    /// 지원 형식:
    /// - https://www.youtube.com/watch?v=xxxxxxxxxxx
    /// - https://youtu.be/xxxxxxxxxxx
    /// - https://www.youtube.com/live/xxxxxxxxxxx
    /// </summary>
    public static string? ExtractVideoId(string url)
    {
        if (string.IsNullOrWhiteSpace(url))
        {
            return null;
        }

        var match = VideoIdRegex().Match(url);
        return match.Success ? match.Groups[1].Value : null;
    }

    [GeneratedRegex(@"youtube\.com/channel/(UC[\w-]+)", RegexOptions.IgnoreCase)]
    private static partial Regex ChannelIdRegex();

    [GeneratedRegex(@"youtube\.com/@([\w.-]+)", RegexOptions.IgnoreCase)]
    private static partial Regex HandleRegex();

    [GeneratedRegex(@"youtube\.com/c/([\w.-]+)", RegexOptions.IgnoreCase)]
    private static partial Regex CustomUrlRegex();

    [GeneratedRegex(@"(?:youtube\.com/watch\?v=|youtu\.be/|youtube\.com/live/)([\w-]{11})", RegexOptions.IgnoreCase)]
    private static partial Regex VideoIdRegex();
}