interface ApiKey {
  id: string;
  name: string;
  prefix: string;
  created: string;
  lastUsed: string;
  status: 'active' | 'revoked';
  scopes: string[];
  key?: string; // Full key (only returned on creation)
}

import { webhookService } from './webhookService';

const STORAGE_KEY = 'veza_dev_api_keys';

interface ApiKey {
  id: string;
  name: string;
  prefix: string;
  created: string;
  lastUsed: string;
  status: 'active' | 'revoked';
  scopes: string[];
  key?: string; // Full key (only returned on creation)
}

const getStoredKeys = (): ApiKey[] => {
  const stored = localStorage.getItem(STORAGE_KEY);
  return stored ? JSON.parse(stored) : [];
};

const saveKeys = (keys: ApiKey[]) => {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(keys));
};

export const developerService = {
  listKeys: async (): Promise<ApiKey[]> => {
    await new Promise((resolve) => setTimeout(resolve, 300));
    return getStoredKeys();
  },

  createKey: async (data: { name: string; scopes: string[] }): Promise<ApiKey> => {
    await new Promise((resolve) => setTimeout(resolve, 600));

    const keyId = Math.random().toString(36).substr(2, 8);
    const keySecret = Math.random().toString(36).substr(2, 16);
    const fullKey = `vz_${keyId}_${keySecret}`;
    const prefix = `vz_${keyId}...`;

    const now = new Date();
    const formattedDate = now.toLocaleDateString('en-US', {
      month: 'short',
      day: 'numeric',
      year: 'numeric'
    });

    const newKey: ApiKey = {
      id: `k-${Date.now()}`,
      name: data.name,
      prefix,
      created: formattedDate,
      lastUsed: 'Never',
      status: 'active',
      scopes: data.scopes,
      key: fullKey,
    };

    const keys = getStoredKeys();
    saveKeys([newKey, ...keys]);

    return newKey;
  },

  revokeKey: async (id: string): Promise<{ success: boolean }> => {
    await new Promise((resolve) => setTimeout(resolve, 300));
    const keys = getStoredKeys();
    const updated = keys.map(k => k.id === id ? { ...k, status: 'revoked' as const } : k);
    saveKeys(updated);
    return { success: true };
  },

  deleteKey: async (id: string): Promise<void> => {
    const keys = getStoredKeys();
    saveKeys(keys.filter(k => k.id !== id));
  },

  getStats: async () => {
    // Mix of real (webhooks) and mock/local (keys) stats
    const keys = getStoredKeys();
    const activeKeys = keys.filter(k => k.status === 'active').length;

    // Fetch real webhook count
    let webhookCount = 0;
    try {
      const hooks = await webhookService.list();
      webhookCount = hooks.length;
    } catch (e) {
      console.error('Failed to fetch webhook stats', e);
    }

    return {
      requests_24h: 145200 + (webhookCount * 1240), // Simulated traffic based on connected hooks
      avg_latency: 45,
      active_keys: activeKeys,
      active_webhooks: webhookCount
    };
  },
};
