import jwt from 'jsonwebtoken';
import { q as query } from './db_Du3AmLCY.mjs';
import { p as parseCookies } from './auth_C2RFIYRJ.mjs';

const JWT_SECRET = process.env.JWT_SECRET || "xK4-pQ9mR2vL7wZn.Yb3jF8hT5dN1cS6";
const COOKIE_NAME = "sp_user";
function signUserToken(payload) {
  return jwt.sign(payload, JWT_SECRET, { expiresIn: "30d" });
}
function verifyUserToken(token) {
  try {
    return jwt.verify(token, JWT_SECRET);
  } catch {
    return null;
  }
}
function getUserFromRequest(request) {
  const cookies = parseCookies(request.headers.get("cookie"));
  const token = cookies[COOKIE_NAME];
  if (!token) return null;
  return verifyUserToken(token);
}
function setUserCookie(token) {
  return `${COOKIE_NAME}=${token}; Path=/; Max-Age=${30 * 86400}; SameSite=Lax; HttpOnly`;
}
function generateToken() {
  return crypto.randomUUID() + "-" + Date.now().toString(36);
}
async function findOrCreateUser(email) {
  const existing = await query("SELECT id, email, email_verified FROM users WHERE email = $1", [email.toLowerCase().trim()]);
  if (existing.rows.length) return existing.rows[0];
  const result = await query(
    "INSERT INTO users (email) VALUES ($1) RETURNING id, email, email_verified",
    [email.toLowerCase().trim()]
  );
  return result.rows[0];
}

export { getUserFromRequest as a, setUserCookie as b, findOrCreateUser as f, generateToken as g, signUserToken as s };
