"use server";

import { revalidatePath } from "next/cache";
import { normalizeMediaUrl } from "./media";
import { prisma } from "./prisma";
import { requireCurrentUser } from "./session";

export async function addMediaToRoom(formData: FormData) {
  const user = await requireCurrentUser();
  const roomId = String(formData.get("roomId") || "");
  const sourceUrl = String(formData.get("sourceUrl") || "").trim();

  if (!roomId || !sourceUrl) return;

  const room = await prisma.room.findFirst({
    where: {
      id: roomId,
      OR: [{ ownerId: user.id }, { members: { some: { userId: user.id } } }, { visibility: "PUBLIC" }]
    },
    select: { id: true, slug: true }
  });

  if (!room) return;

  const media = normalizeMediaUrl(sourceUrl);
  await prisma.mediaSource.create({
    data: {
      roomId: room.id,
      submitterId: user.id,
      provider: media.provider,
      originalUrl: media.originalUrl,
      playbackUrl: media.playbackUrl,
      title: media.originalUrl
    }
  });

  await prisma.room.update({
    where: { id: room.id },
    data: {
      currentState: {
        provider: media.provider,
        originalUrl: media.originalUrl,
        playbackUrl: media.playbackUrl,
        updatedBy: user.username,
        updatedAt: Date.now()
      }
    }
  });

  revalidatePath(`/rooms/${encodeURIComponent(room.slug)}`);
  revalidatePath("/dashboard");
}
