import "server-only";

import fs from "node:fs";
import path from "node:path";

import { MediaProcessingError } from "@/lib/server/media-errors";

type SocialProvider = "instagram" | "tiktok" | "twitter" | "youtube";

interface YtDlpAuthOptions {
  cookies?: string;
}

function resolveExistingFileFromEnv(variableName: string): string | null {
  const rawValue = process.env[variableName]?.trim();
  if (!rawValue) {
    return null;
  }

  const candidatePath = path.isAbsolute(rawValue) ? rawValue : path.resolve(rawValue);
  if (!fs.existsSync(candidatePath)) {
    throw new MediaProcessingError({
      message: `${variableName} points to '${candidatePath}', but that file does not exist.`,
      code: "filesystem_failure",
      statusCode: 500
    });
  }

  return candidatePath;
}

function getProviderCookieEnvVariable(provider: SocialProvider) {
  switch (provider) {
    case "instagram":
      return "INSTAGRAM_COOKIES_PATH";
    case "tiktok":
      return "TIKTOK_COOKIES_PATH";
    case "twitter":
      return "TWITTER_COOKIES_PATH";
    case "youtube":
      return "YOUTUBE_COOKIES_PATH";
    default:
      return null;
  }
}

export function getYtDlpAuthOptions(provider: SocialProvider): YtDlpAuthOptions {
  const providerVariableName = getProviderCookieEnvVariable(provider);
  const providerCookiesPath = providerVariableName
    ? resolveExistingFileFromEnv(providerVariableName)
    : null;
  const sharedCookiesPath = resolveExistingFileFromEnv("YT_DLP_COOKIES_PATH");
  const cookiesPath = providerCookiesPath || sharedCookiesPath;

  if (!cookiesPath) {
    return {};
  }

  return {
    cookies: cookiesPath
  };
}
