'use server';

import { listApiKeys as listApiKeysQuery } from '../db/queries/apiKeys';

const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000';

interface BootstrapResponse {
  apiKey: string;
  type: string;
  name: string;
  expiresAt: string | null;
  message: string;
}

interface CreateKeyResponse {
  apiKey: string;
  metadata: {
    id: string;
    type: string;
    projectId: string;
    name: string;
    expiresAt: string | null;
    scopes: string[];
    createdAt: string;
  };
  message: string;
}

export async function bootstrapMasterKey(): Promise<{
  success: boolean;
  apiKey?: string;
  error?: string;
}> {
  try {
    const response = await fetch(`${API_BASE_URL}/api/bootstrap/initial-key`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
    });

    if (!response.ok) {
      const error = await response.json();
      return { success: false, error: error.message || 'Failed to bootstrap master key' };
    }

    const data: BootstrapResponse = await response.json();
    return { success: true, apiKey: data.apiKey };
  } catch (error) {
    console.error('Bootstrap error:', error);
    return { success: false, error: 'Network error while bootstrapping master key' };
  }
}

export async function createProjectApiKey(
  masterKey: string,
  orgSlug: string,
  projectSlug: string,
): Promise<{ success: boolean; apiKey?: string; error?: string }> {
  try {
    // Call API service to create the project key (API auto-creates org/project)
    const response = await fetch(`${API_BASE_URL}/api/admin/keys`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-API-Key': masterKey,
      },
      body: JSON.stringify({
        type: 'project',
        organizationSlug: orgSlug,
        projectSlug: projectSlug,
        name: `${orgSlug} - ${projectSlug}`,
      }),
    });

    if (!response.ok) {
      const error = await response.json();
      return { success: false, error: error.message || 'Failed to create API key' };
    }

    const data: CreateKeyResponse = await response.json();
    return { success: true, apiKey: data.apiKey };
  } catch (error) {
    console.error('Create key error:', error);
    return { success: false, error: 'Network error while creating API key' };
  }
}

export async function listApiKeys() {
  try {
    return await listApiKeysQuery();
  } catch (error) {
    console.error('List keys error:', error);
    return [];
  }
}
