import { db } from '../client';
import { apiKeys, organizations, projects, type ApiKey } from '@banatie/database';
import { eq, desc } from 'drizzle-orm';

export async function listApiKeys() {
  return db
    .select({
      id: apiKeys.id,
      keyType: apiKeys.keyType,
      name: apiKeys.name,
      scopes: apiKeys.scopes,
      isActive: apiKeys.isActive,
      createdAt: apiKeys.createdAt,
      expiresAt: apiKeys.expiresAt,
      lastUsedAt: apiKeys.lastUsedAt,
      organizationId: apiKeys.organizationId,
      organizationName: organizations.name,
      organizationEmail: organizations.email,
      projectId: apiKeys.projectId,
      projectName: projects.name,
    })
    .from(apiKeys)
    .leftJoin(organizations, eq(apiKeys.organizationId, organizations.id))
    .leftJoin(projects, eq(apiKeys.projectId, projects.id))
    .orderBy(desc(apiKeys.createdAt))
    .limit(50);
}

export async function getApiKeysByProject(projectId: string) {
  return db
    .select()
    .from(apiKeys)
    .where(eq(apiKeys.projectId, projectId))
    .orderBy(desc(apiKeys.createdAt));
}
