import jwt from 'jsonwebtoken';

const DEFAULT_SECRET = process.env.JWT_SECRET || 'my-plan-app-secret-key-change-this';
const TOKEN_EXPIRY = '30d';

export function signToken(payload: Record<string, unknown>, secret?: string): string {
  return jwt.sign(payload, secret || DEFAULT_SECRET, { expiresIn: TOKEN_EXPIRY });
}

export function verifyToken(token: string, secret?: string): Record<string, unknown> | null {
  try {
    return jwt.verify(token, secret || DEFAULT_SECRET) as Record<string, unknown>;
  } catch {
    return null;
  }
}

export function extractTokenFromHeader(authHeader: string | null): string | null {
  if (!authHeader || !authHeader.startsWith('Bearer ')) return null;
  return authHeader.slice(7);
}

export function validateRequest(request: Request): { valid: boolean; error?: string } {
  const authHeader = request.headers.get('Authorization');
  const token = extractTokenFromHeader(authHeader);
  if (!token) return { valid: false, error: 'No token provided' };

  const secret = process.env.JWT_SECRET || DEFAULT_SECRET;
  const decoded = verifyToken(token, secret);
  if (!decoded) return { valid: false, error: 'Invalid or expired token' };

  return { valid: true };
}
