import apiClient from './client'

export interface Bucket {
  name: string
  creation_date: string
  size: number
  objects: number
  access_policy: 'private' | 'public-read' | 'public-read-write'
}

export const objectStorageApi = {
  listBuckets: async (): Promise<Bucket[]> => {
    const response = await apiClient.get<{ buckets: Bucket[] }>('/object-storage/buckets')
    return response.data.buckets || []
  },

  getBucket: async (name: string): Promise<Bucket> => {
    const response = await apiClient.get<Bucket>(`/object-storage/buckets/${encodeURIComponent(name)}`)
    return response.data
  },

  createBucket: async (name: string): Promise<void> => {
    await apiClient.post('/object-storage/buckets', { name })
  },

  deleteBucket: async (name: string): Promise<void> => {
    await apiClient.delete(`/object-storage/buckets/${encodeURIComponent(name)}`)
  },

  // Setup endpoints
  getAvailableDatasets: async (): Promise<PoolDatasetInfo[]> => {
    const response = await apiClient.get<{ pools: PoolDatasetInfo[] }>('/object-storage/setup/datasets')
    return response.data.pools || []
  },

  getCurrentSetup: async (): Promise<CurrentSetup | null> => {
    const response = await apiClient.get<{ configured: boolean; setup?: SetupResponse }>('/object-storage/setup/current')
    if (!response.data.configured || !response.data.setup) {
      return null
    }
    return {
      dataset_path: response.data.setup.dataset_path,
      mount_point: response.data.setup.mount_point,
    }
  },

  setupObjectStorage: async (poolName: string, datasetName: string, createNew: boolean): Promise<SetupResponse> => {
    const response = await apiClient.post<SetupResponse>('/object-storage/setup', {
      pool_name: poolName,
      dataset_name: datasetName,
      create_new: createNew,
    })
    return response.data
  },

  updateObjectStorage: async (poolName: string, datasetName: string, createNew: boolean): Promise<SetupResponse> => {
    const response = await apiClient.put<SetupResponse>('/object-storage/setup', {
      pool_name: poolName,
      dataset_name: datasetName,
      create_new: createNew,
    })
    return response.data
  },

  // User management
  listUsers: async (): Promise<User[]> => {
    const response = await apiClient.get<{ users: User[] }>('/object-storage/users')
    return response.data.users || []
  },

  createUser: async (data: CreateUserRequest): Promise<void> => {
    await apiClient.post('/object-storage/users', data)
  },

  deleteUser: async (accessKey: string): Promise<void> => {
    await apiClient.delete(`/object-storage/users/${encodeURIComponent(accessKey)}`)
  },

  // Service account (access key) management
  listServiceAccounts: async (): Promise<ServiceAccount[]> => {
    const response = await apiClient.get<{ service_accounts: ServiceAccount[] }>('/object-storage/service-accounts')
    return response.data.service_accounts || []
  },

  createServiceAccount: async (data: CreateServiceAccountRequest): Promise<ServiceAccount> => {
    const response = await apiClient.post<ServiceAccount>('/object-storage/service-accounts', data)
    return response.data
  },

  deleteServiceAccount: async (accessKey: string): Promise<void> => {
    await apiClient.delete(`/object-storage/service-accounts/${encodeURIComponent(accessKey)}`)
  },

  // Object browsing
  listObjects: async (bucketName: string, prefix?: string): Promise<Object[]> => {
    const params = prefix ? `?prefix=${encodeURIComponent(prefix)}` : ''
    const response = await apiClient.get<{ objects: Object[] }>(`/object-storage/buckets/${encodeURIComponent(bucketName)}/objects${params}`)
    return response.data.objects || []
  },
}

export interface PoolDatasetInfo {
  pool_id: string
  pool_name: string
  datasets: DatasetInfo[]
}

export interface DatasetInfo {
  id: string
  name: string
  full_name: string
  mount_point: string
  type: string
  used_bytes: number
  available_bytes: number
}

export interface SetupResponse {
  dataset_path: string
  mount_point: string
  message: string
}

export interface CurrentSetup {
  dataset_path: string
  mount_point: string
}

export interface User {
  access_key: string
  status: 'enabled' | 'disabled'
  created_at: string
}

export interface ServiceAccount {
  access_key: string
  secret_key?: string // Only returned on creation
  parent_user: string
  expiration?: string
  created_at: string
}

export interface CreateUserRequest {
  access_key: string
  secret_key: string
}

export interface CreateServiceAccountRequest {
  parent_user: string
  policy?: string
  expiration?: string // ISO 8601 format
}

export interface Object {
  name: string
  key: string // Full path/key
  size: number // Size in bytes (0 for folders)
  last_modified: string
  is_dir: boolean // True if this is a folder/prefix
  etag?: string
}
