import { SignJWT, jwtVerify } from 'jose';
import { db } from '@/lib/db';
import { signingTokens } from '@/lib/db/schema';

const getSecret = () => new TextEncoder().encode(process.env.SIGNING_JWT_SECRET!);

export async function createSigningToken(documentId: string): Promise<{ token: string; jti: string; expiresAt: Date }> {
  const jti = crypto.randomUUID();
  const expiresAt = new Date(Date.now() + 72 * 60 * 60 * 1000); // 72 hours

  const token = await new SignJWT({ documentId, purpose: 'sign' })
    .setProtectedHeader({ alg: 'HS256' })
    .setIssuedAt()
    .setExpirationTime('72h')
    .setJti(jti)
    .sign(getSecret());

  // Store token metadata for one-time-use enforcement
  await db.insert(signingTokens).values({
    jti,
    documentId,
    expiresAt,
  });

  return { token, jti, expiresAt };
}

export async function verifySigningToken(token: string): Promise<{ documentId: string; jti: string; exp: number }> {
  // Throws JWTExpired or JWTInvalid on failure — caller handles
  const { payload } = await jwtVerify(token, getSecret());
  return payload as { documentId: string; jti: string; exp: number };
}
