import { db } from './config';
import { doc, getDoc, setDoc, serverTimestamp } from 'firebase/firestore';
import { v4 as uuidv4 } from 'uuid';

interface ApiKey {
  key: string;
  userId: string;
  createdAt: any;
  lastUsed?: any;
  isActive: boolean;
}

// Generate a new API key for a user
export async function generateApiKey(userId: string): Promise<string> {
  const apiKey = `vibn_${uuidv4().replace(/-/g, '')}`;
  
  const keyDoc = doc(db, 'apiKeys', apiKey);
  await setDoc(keyDoc, {
    key: apiKey,
    userId,
    createdAt: serverTimestamp(),
    isActive: true,
  });
  
  return apiKey;
}

// Get or create API key for a user
export async function getOrCreateApiKey(userId: string): Promise<string> {
  // Check if user already has an API key
  const userDoc = doc(db, 'users', userId);
  const userSnap = await getDoc(userDoc);
  
  if (userSnap.exists() && userSnap.data().apiKey) {
    return userSnap.data().apiKey;
  }
  
  // Generate new key
  const apiKey = await generateApiKey(userId);
  
  // Store reference in user document
  await setDoc(userDoc, {
    apiKey,
    updatedAt: serverTimestamp(),
  }, { merge: true });
  
  return apiKey;
}

// Verify an API key and return the userId
export async function verifyApiKey(apiKey: string): Promise<string | null> {
  try {
    const keyDoc = doc(db, 'apiKeys', apiKey);
    const keySnap = await getDoc(keyDoc);
    
    if (!keySnap.exists() || !keySnap.data().isActive) {
      return null;
    }
    
    // Update last used timestamp
    await setDoc(keyDoc, {
      lastUsed: serverTimestamp(),
    }, { merge: true });
    
    return keySnap.data().userId;
  } catch (error) {
    console.error('Error verifying API key:', error);
    return null;
  }
}

