"use server";

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

export async function sendFriendRequest(formData: FormData) {
  const user = await requireCurrentUser();
  const receiverId = String(formData.get("receiverId") || "");

  if (!receiverId || receiverId === user.id) return;

  const existing = await prisma.friendship.findFirst({
    where: {
      OR: [
        { requesterId: user.id, receiverId },
        { requesterId: receiverId, receiverId: user.id }
      ]
    },
    select: { id: true, status: true }
  });

  if (!existing) {
    await prisma.friendship.create({
      data: {
        requesterId: user.id,
        receiverId,
        status: "PENDING"
      }
    });
  } else if (existing.status === "DECLINED") {
    await prisma.friendship.update({
      where: { id: existing.id },
      data: {
        requesterId: user.id,
        receiverId,
        status: "PENDING"
      }
    });
  }

  revalidatePath("/friends");
  revalidatePath("/dashboard");
}

export async function acceptFriendRequest(formData: FormData) {
  await updateIncomingRequest(formData, "ACCEPTED");
}

export async function declineFriendRequest(formData: FormData) {
  await updateIncomingRequest(formData, "DECLINED");
}

async function updateIncomingRequest(formData: FormData, status: "ACCEPTED" | "DECLINED") {
  const user = await requireCurrentUser();
  const friendshipId = String(formData.get("friendshipId") || "");
  if (!friendshipId) return;

  await prisma.friendship.updateMany({
    where: {
      id: friendshipId,
      receiverId: user.id,
      status: "PENDING"
    },
    data: { status }
  });

  revalidatePath("/friends");
  revalidatePath("/dashboard");
}
