import { prisma } from '@/lib/db';

/**
 * Validate preview token for draft reads
 */
export async function validatePreviewToken(
  token: string | null,
  section: string,
  lang: string
): Promise<boolean> {
  if (!token) return false;

  const record = await prisma.preview_tokens.findUnique({
    where: { token },
  });

  if (!record) return false;
  if (record.expiresAt < new Date()) return false;

  const scopes: string[] = Array.isArray(record.scopes) ? (record.scopes as string[]) : [];
  if (scopes.includes('all')) return true;
  if (scopes.includes(section)) return true;
  if (scopes.includes(`${section}:${lang}`)) return true;

  return false;
}

/**
 * Persist a version snapshot for auditing/rollback
 */
export async function saveContentVersion(
  entityType: string,
  entityId: string,
  version: number,
  snapshot: Record<string, any>,
  userId?: string
) {
  try {
    await prisma.content_versions.create({
      data: {
        entityType,
        entityId,
        version,
        snapshot,
        createdBy: userId,
      },
    });
  } catch (error) {
    console.error('[site-content] Failed to save content version', error);
  }
}
