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

namespace Application.Features.Api.Channel.Get;

public sealed class Handler(IAppDbContext db, IYouTubeLiveStateStore liveStateStore, IYouTubeChannelCache channelCache) : IQueryHandler<Query, Result<Response>>
{
    public async Task<Result<Response>> Handle(Query request, CancellationToken ct)
    {
        var channel = await db.Channel.AsNoTracking().FirstOrDefaultAsync(c => c.SID == request.ChannelSID && c.IsActive, ct);

        if (channel is null)
        {
            return Result.Failure<Response>(Error.NotFound("Channel.NotFound", "채널을 찾을 수 없습니다."));
        }

        var liveInfo = await liveStateStore.GetLiveAsync(channel.SID);
        var ytInfo = await channelCache.GetAsync(channel.SID);

        return new Response(
            channel.SID,
            channel.Name,
            channel.Handle,
            channel.YouTubeUrl,
            ytInfo?.ThumbnailUrl,
            ytInfo?.BannerUrl,
            ytInfo?.Description,
            ytInfo?.SubscriberCount ?? 0,
            ytInfo?.VideoCount ?? 0,
            channel.IsVerified,
            liveInfo is not null,
            liveInfo?.VideoId,
            liveInfo?.Title
        );
    }
}