import { z } from "zod";

export type NormalizedMedia = {
  provider: "YOUTUBE" | "TWITCH" | "DIRECT" | "UNKNOWN";
  originalUrl: string;
  playbackUrl: string;
  thumbnailUrl?: string;
  title?: string;
};

const urlSchema = z.string().url();

const YOUTUBE_HOSTS = new Set(["youtube.com", "www.youtube.com", "m.youtube.com", "youtu.be"]);
const TWITCH_HOSTS = new Set(["twitch.tv", "www.twitch.tv", "m.twitch.tv"]);
const DIRECT_VIDEO_EXTENSIONS = [".mp4", ".webm", ".ogg", ".mov", ".m4v"];

export function normalizeMediaUrl(input: string): NormalizedMedia {
  const originalUrl = input.trim();
  const parsedInput = urlSchema.safeParse(originalUrl);

  if (!parsedInput.success) {
    return {
      provider: "UNKNOWN",
      originalUrl,
      playbackUrl: originalUrl
    };
  }

  const url = new URL(parsedInput.data);
  const host = url.hostname.toLowerCase();

  if (YOUTUBE_HOSTS.has(host)) {
    const id = getYoutubeId(url);
    if (id) {
      return {
        provider: "YOUTUBE",
        originalUrl,
        thumbnailUrl: `https://img.youtube.com/vi/${id}/hqdefault.jpg`,
        playbackUrl: `https://www.youtube.com/embed/${id}?enablejsapi=1&origin=${encodeURIComponent(
          process.env.NEXTAUTH_URL || "http://localhost:3000"
        )}`
      };
    }
  }

  if (TWITCH_HOSTS.has(host)) {
    const parts = url.pathname.split("/").filter(Boolean);
    const parent = new URL(process.env.NEXTAUTH_URL || "http://localhost:3000").hostname;
    if (parts[0] === "videos" && parts[1]) {
      return {
        provider: "TWITCH",
        originalUrl,
        thumbnailUrl: "/watchlink-icon-64.png",
        playbackUrl: `https://player.twitch.tv/?video=${parts[1]}&parent=${parent}`
      };
    }
    if (parts[0]) {
      return {
        provider: "TWITCH",
        originalUrl,
        thumbnailUrl: "/watchlink-icon-64.png",
        playbackUrl: `https://player.twitch.tv/?channel=${parts[0]}&parent=${parent}`
      };
    }
  }

  if (DIRECT_VIDEO_EXTENSIONS.some((extension) => url.pathname.toLowerCase().endsWith(extension))) {
    return {
      provider: "DIRECT",
      originalUrl,
      thumbnailUrl: "/watchlink-icon-64.png",
      playbackUrl: originalUrl
    };
  }

  return {
    provider: "UNKNOWN",
    originalUrl,
    playbackUrl: originalUrl
  };
}

function getYoutubeId(url: URL) {
  if (url.hostname === "youtu.be") {
    return url.pathname.split("/").filter(Boolean)[0];
  }

  if (url.pathname === "/watch") {
    return url.searchParams.get("v");
  }

  const parts = url.pathname.split("/").filter(Boolean);
  if (["embed", "shorts", "live"].includes(parts[0])) {
    return parts[1];
  }

  return null;
}
