var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
import { z } from 'zod';
import { recursiveFetch } from '../../../helpers/fetch.js';
export const ZTikTokVideoItem = z.object({
    id: z.string().uuid().optional(),
    moduleId: z.string().optional().nullable(),
    order: z.number().optional(),
    url: z.string().optional().nullable(),
    versionId: z.string().optional().nullable(),
    visible: z.boolean().default(true)
});
export const tiktokVideoRegex = /^(?:https:\/\/)?(?:www.)?tiktok.(?:com)\/@(.+)\/video\/([0-9]+)/;
export const tiktokResolvableUrlRegex = /^(?:https?:\/\/)?(?:www\.)?(?:vm\.|vt\.)?tiktok\.com\/(?:t\/)?([A-Za-z0-9]+)/;
export function resolveTikTokURL(url) {
    return __awaiter(this, void 0, void 0, function* () {
        if (tiktokVideoRegex.test(url)) {
            return url;
        }
        if (!tiktokResolvableUrlRegex.test(url)) {
            throw new Error('Invalid TikTok URL');
        }
        const { url: finalUrl } = yield recursiveFetch(url);
        const match = finalUrl.match(tiktokVideoRegex);
        if (!match || match.length < 3) {
            throw new Error('Resolved URL not a valid video URL');
        }
        return `https://www.tiktok.com/@${match[1]}/video/${match[2]}`;
    });
}
export const ZTikTokResolveBody = z.object({
    url: z.string().url()
});
