import { apiClient } from './api'

export interface APIKeyScope {
  value: string
  label: string
}

export interface APIKey {
  id: number
  user_id: number
  name: string
  scopes: string[]
  is_active: boolean
  expires_at?: string
  last_used_at?: string
  created_at: string
  user_email?: string
}

export interface APIKeyCreate {
  name: string
  scopes: string[]
  expires_at?: string
  user_id?: number
}

export interface APIKeyWithToken {
  api_key: APIKey
  token: string
}

export interface APIKeyUpdate {
  name?: string
  scopes?: string[]
  is_active?: boolean
  expires_at?: string
}

export const apiKeyService = {
  async createAPIKey(data: APIKeyCreate): Promise<APIKeyWithToken> {
    const response = await apiClient.post('/auth/api-keys', data)
    return response.data
  },

  async getAPIKeys(userId?: number): Promise<APIKey[]> {
    const params = userId ? { user_id: userId } : {}
    const response = await apiClient.get('/auth/api-keys', { params })
    return response.data
  },

  async updateAPIKey(keyId: number, data: APIKeyUpdate): Promise<APIKey> {
    const response = await apiClient.put(`/auth/api-keys/${keyId}`, data)
    return response.data
  },

  async deleteAPIKey(keyId: number): Promise<void> {
    await apiClient.delete(`/auth/api-keys/${keyId}`)
  },

  async getAPIKeyUsage(keyId: number): Promise<any[]> {
    const response = await apiClient.get(`/auth/api-keys/${keyId}/usage`)
    return response.data
  }
}

export const API_KEY_SCOPES: APIKeyScope[] = [
  { value: 'read:projects', label: 'Read Projects' },
  { value: 'read:tasks', label: 'Read Tasks' },
  { value: 'read:submissions', label: 'Read Submissions' },
  { value: 'read:users', label: 'Read Users' },
  { value: 'write:tasks', label: 'Write Tasks' },
  { value: 'write:submissions', label: 'Write Submissions' },
  { value: 'admin:users', label: 'Admin Users' },
  { value: 'full:access', label: 'Full Access' }
]