import { createClient } from "@/utils/supabase/server"; import { redirect } from "next/navigation"; import { sendFriendRequest } from "@/utils/friends/friends"; import { UUID_REGEX } from "@/utils/validation"; import Link from "next/link"; type ResultStatus = "success" | "already_friends" | "error"; export default async function AddFriendPage({ searchParams, }: Readonly<{ searchParams: Promise<{ id?: string }>; }>) { const { id } = await searchParams; // Validate the ID parameter if (!id || !UUID_REGEX.test(id)) { return (
); } const supabase = await createClient(); const { data: { user }, } = await supabase.auth.getUser(); // Must be authenticated — redirect to login with return URL if (!user) { redirect(`/login?next=%2Ffriends%2Fadd%3Fid%3D${id}`); } // Can't add yourself if (user.id === id) { return (
); } // Look up the target user const { data: targetUser } = await supabase .from("users") .select("id, name") .eq("id", id) .single(); if (!targetUser) { return (
); } // Check if already friends const { data: existing } = await supabase .from("friends") .select("user_id") .eq("user_id", user.id) .eq("friend_id", id) .maybeSingle(); if (existing) { return (
); } // Send the friend request let status: ResultStatus; let message: string; try { const sent = await sendFriendRequest(id); if (sent === false) { status = "error"; message = "Could not send friend request. It may already exist."; } else { status = "success"; message = `Friend request sent to ${targetUser.name}!`; } } catch { status = "error"; message = "Something went wrong. Please try again."; } return (
); } function ResultCard({ status, message, }: Readonly<{ status: ResultStatus; message: string; }>) { const isSuccess = status === "success"; const isAlreadyFriends = status === "already_friends"; return (
{isSuccess ? ( ) : isAlreadyFriends ? ( ) : ( )}

{isSuccess ? "Request Sent!" : isAlreadyFriends ? "Already Friends" : "Something went wrong"}

{message}

Back to Friends Go to Rooms
); }