import { cleanNumber, extractNumber } from '$lib/numbers';
import { convertToSeconds } from '$lib/time';
import type { Channel, Playlist, Thumbnail, Video } from '../model';
import { Helpers, YTNodes } from 'youtubei.js';

export function invidiousItemSchema(item: Helpers.YTNode): Video | Channel | Playlist | undefined {
	if (item.is(YTNodes.Video)) {
		const views = extractNumber(item.view_count?.toString() || '');
		return {
			type: 'video',
			title: item.title.toString(),
			videoId: item.video_id,
			viewCountText: cleanNumber(views),
			viewCount: views,
			videoThumbnails: item.thumbnails as Thumbnail[],
			published: 0,
			publishedText: item.published?.toString() || '',
			description: '',
			descriptionHtml: '',
			authorUrl: `/channel/${item.author.id}`,
			authorId: item.author.id,
			authorVerified: false,
			liveNow: false,
			isUpcoming: false,
			premium: false,
			author: item.author.name,
			lengthSeconds: item.length_text?.text ? convertToSeconds(item.length_text.text) : 0
		};
	} else if (item.is(YTNodes.Channel)) {
		return {
			type: 'channel',
			authorId: item.id,
			author: item.author.name,
			authorUrl: `/channel/${item.id}`,
			authorVerified: item.author.is_verified === true,
			subCount: item.video_count.text ? extractNumber(item.video_count.text) : 0,
			totalViews: 0,
			autoGenerated: false,
			description: item.description_snippet.text ?? '',
			descriptionHml: item.description_snippet.toHTML() ?? '',
			authorThumbnails: item.author.thumbnails as Thumbnail[]
		};
	} else if (item.is(YTNodes.LockupView) && item.content_type === 'PLAYLIST') {
		let author = '';
		const metadataRows = item.metadata?.metadata?.metadata_rows[0];
		if (metadataRows && metadataRows.metadata_parts) {
			author = metadataRows.metadata_parts[0].text?.text ?? '';
		}
		return {
			type: 'playlist',
			title: item.metadata?.title.text ?? '',
			playlistId: item.content_id,
			playlistThumbnail: item.content_image?.is(YTNodes.CollectionThumbnailView)
				? item.content_image.primary_thumbnail?.is(YTNodes.ThumbnailView)
					? item.content_image.primary_thumbnail.image[0].url
					: ''
				: '',
			authorVerified: false,
			author,
			authorId: '',
			videoCount: 0,
			videos: []
		};
	}
}
