import type { Plan } from "@prisma/client";
import { hasProFeatures } from "../edition";
import type { CreateJobPayload, CreatePlaylistRequest, ItemMetadata } from "../types";
import { createYouTubePlaylist } from "../youtube/upload";

export function parseCreatePlaylistInput(raw: unknown): CreatePlaylistRequest | null {
  if (!raw || typeof raw !== "object") return null;
  const value = raw as Record<string, unknown>;
  const title = typeof value.title === "string" ? value.title.trim() : "";
  if (!title) return null;

  const privacy =
    value.privacy === "public" || value.privacy === "unlisted" || value.privacy === "private"
      ? value.privacy
      : undefined;

  return {
    title,
    description: typeof value.description === "string" ? value.description : undefined,
    privacy,
  };
}

export async function applyCreatePlaylistToItems(
  user: { id: string; plan: Plan },
  items: CreateJobPayload["items"],
  createPlaylist: CreatePlaylistRequest | null | undefined,
) {
  if (!createPlaylist) {
    return { items, playlist: null as Awaited<ReturnType<typeof createYouTubePlaylist>> | null };
  }

  if (!hasProFeatures(user.plan)) {
    throw new Error("Creating a YouTube playlist requires the Pro plan");
  }

  const playlist = await createYouTubePlaylist(user.id, createPlaylist);
  const nextItems = items.map((item) => ({
    ...item,
    metadata: {
      ...item.metadata,
      playlistId: item.metadata.playlistId || playlist.id,
    } satisfies ItemMetadata,
  }));

  return { items: nextItems, playlist };
}
