import { ApisauceInstance, create } from "apisauce";

export interface TikTokVideoMetadata {
  type: "video";
  title: string;
  author_url: string;
  author_name: string;
  width: string;
  height: string;
  html: string;
  thumbnail_url: string;
  thumbnail_width: string;
  thumbnail_height: string;
  author_unique_id: string;
  embed_product_id: string;
  embed_type: string;
}

export interface TikTokUnavailableMetadata {
  type: "unavailable";
}

export type TikTokOEmbedMetadata =
  | TikTokVideoMetadata
  | TikTokUnavailableMetadata;

const unavailable = {
  type: "unavailable",
} as TikTokUnavailableMetadata;

class TikTokOEmbed {
  api: ApisauceInstance;
  constructor() {
    this.api = create({
      baseURL: "https://www.tiktok.com",
      timeout: 10000,
    });
  }

  async metadata(url: string): Promise<TikTokOEmbedMetadata> {
    const response = await this.api.get<TikTokOEmbedMetadata>(
      `oembed?url=${url}`
    );

    if (!response.ok || response.data?.type !== "video") {
      return unavailable;
    }

    return response.data || unavailable;
  }
}

export default new TikTokOEmbed();
