import jwt from 'jsonwebtoken';
import { query } from './db';
import { parseCookies } from './auth';

const JWT_SECRET = process.env.JWT_SECRET || import.meta.env?.JWT_SECRET || 'sneakerpicks-dev-secret';
const COOKIE_NAME = 'sp_user';

export interface UserPayload {
  id: string;
  email: string;
}

export function signUserToken(payload: UserPayload): string {
  return jwt.sign(payload, JWT_SECRET, { expiresIn: '30d' });
}

export function verifyUserToken(token: string): UserPayload | null {
  try {
    return jwt.verify(token, JWT_SECRET) as UserPayload;
  } catch {
    return null;
  }
}

export function getUserFromRequest(request: Request): UserPayload | null {
  const cookies = parseCookies(request.headers.get('cookie'));
  const token = cookies[COOKIE_NAME];
  if (!token) return null;
  return verifyUserToken(token);
}

export function setUserCookie(token: string): string {
  return `${COOKIE_NAME}=${token}; Path=/; Max-Age=${30 * 86400}; SameSite=Lax; HttpOnly`;
}

export function clearUserCookie(): string {
  return `${COOKIE_NAME}=; Path=/; Max-Age=0; SameSite=Lax; HttpOnly`;
}

export function generateToken(): string {
  return crypto.randomUUID() + '-' + Date.now().toString(36);
}

export async function findOrCreateUser(email: string): Promise<{ id: string; email: string; email_verified: boolean }> {
  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];
}
