/**
 * Venue lookup for the join page (server only: imported by server components). Mirrors the game
 * server's resolveJoin: join codes match case-insensitively, cancelled venues don't exist, rooms are
 * ACTIVE ones in creation order (the first is the default when a QR code carries no room).
 */
import { cache } from 'react';
import { getDb } from '@pintrush/db';

/** Same shape the protocol accepts for `room.join` (VenueCodeSchema). */
const JOIN_CODE = /^[A-Za-z0-9]{2,12}$/;

export interface JoinVenue {
  id: string;
  name: string;
  joinCode: string;
  rooms: { id: string; name: string }[];
}

/** Cached per request so generateMetadata and the page share one query. */
export const findJoinVenue = cache(async (code: string): Promise<JoinVenue | null> => {
  if (!JOIN_CODE.test(code)) return null;
  return getDb().venue.findFirst({
    where: { joinCode: { equals: code, mode: 'insensitive' }, status: { not: 'CANCELLED' } },
    select: {
      id: true,
      name: true,
      joinCode: true,
      rooms: { where: { status: 'ACTIVE' }, orderBy: { createdAt: 'asc' }, select: { id: true, name: true } },
    },
  });
});

export function isJoinCode(code: string): boolean {
  return JOIN_CODE.test(code);
}
