/**
 * Magic-link queries - for guest→user email conversion.
 */

import { eq } from 'drizzle-orm';
import type { DrizzleClient } from '../client.js';
import { magicLinks } from '../schema.js';

export async function create(
  db: DrizzleClient,
  input: {
    id: string;
    tokenHash: string;
    /** Encrypted email SQL fragment. */
    emailEncrypted: unknown;
    preFill?: Record<string, unknown>;
    expiresAt: Date;
  },
) {
  const [row] = await db
    .insert(magicLinks)
    .values({
      id: input.id,
      tokenHash: input.tokenHash,
      emailEncrypted: input.emailEncrypted as string,
      preFill: input.preFill,
      expiresAt: input.expiresAt,
    })
    .returning();
  return row!;
}

/**
 * Find a valid magic-link by its token hash.
 * Returns null if not found, already used, or expired.
 */
export async function findByTokenHash(db: DrizzleClient, tokenHash: string) {
  const [row] = await db
    .select()
    .from(magicLinks)
    .where(eq(magicLinks.tokenHash, tokenHash))
    .limit(1);
  if (!row) return null;
  if (row.usedAt) return null;
  if (row.expiresAt < new Date()) return null;
  return row;
}

/**
 * Mark a magic-link as consumed. Returns null if not found or already used.
 */
export async function consume(db: DrizzleClient, tokenHash: string) {
  const link = await findByTokenHash(db, tokenHash);
  if (!link) return null;

  const [row] = await db
    .update(magicLinks)
    .set({ usedAt: link.usedAt ?? new Date() })
    .where(eq(magicLinks.tokenHash, tokenHash))
    .returning();
  return row ?? null;
}
