import apiClient from './client'

// ============================================================================
// Types
// ============================================================================

export interface SCSTTarget {
  id: string
  iqn: string
  alias?: string
  is_active: boolean
  lun_count?: number
  created_at: string
  updated_at: string
}

export interface SCSTLUN {
  id: string
  target_id: string
  lun_number: number
  handler: string
  device_path: string
  device_type: string
  is_active: boolean
  created_at: string
  updated_at: string
}

export interface SCSTInitiator {
  id: string
  group_id: string
  iqn: string
  is_active: boolean
  created_at: string
  updated_at?: string
  target_id?: string
  target_iqn?: string
  target_name?: string
  group_name?: string
}

export interface SCSTInitiatorGroup {
  id: string
  target_id: string
  group_name: string
  initiators: SCSTInitiator[]
  created_at: string
  updated_at: string
}

export interface SCSTHandler {
  name: string
  label: string
  description?: string
}

export interface SCSTPortal {
  id: string
  ip_address: string
  port: number
  is_active: boolean
  created_at: string
  updated_at: string
}

export interface CreateTargetRequest {
  iqn: string
  target_type: string
  name: string
  description?: string
  single_initiator_only?: boolean
}

export interface AddLUNRequest {
  device_name: string
  device_path: string
  lun_number: number
  handler_type: string
}

export interface AddInitiatorRequest {
  initiator_iqn: string
}

// ============================================================================
// SCST API
// ============================================================================

export const scstAPI = {
  listTargets: async (): Promise<SCSTTarget[]> => {
    const response = await apiClient.get('/scst/targets', {
      headers: {
        'Cache-Control': 'no-cache',
      },
      params: {
        _t: Date.now(), // Add timestamp to prevent browser caching
      },
    })
    return response.data.targets || []
  },

  getTarget: async (id: string): Promise<{
    target: SCSTTarget
    luns: SCSTLUN[]
    initiator_groups?: SCSTInitiatorGroup[]
  }> => {
    const response = await apiClient.get(`/scst/targets/${id}`, {
      headers: {
        'Cache-Control': 'no-cache',
      },
      params: {
        _t: Date.now(), // Add timestamp to prevent browser caching
      },
    })
    return response.data
  },

  createTarget: async (data: CreateTargetRequest): Promise<SCSTTarget> => {
    const response = await apiClient.post('/scst/targets', data)
    // Backend returns target directly, not wrapped in { target: ... }
    return response.data
  },

  addLUN: async (targetId: string, data: AddLUNRequest): Promise<{ task_id: string }> => {
    const response = await apiClient.post(`/scst/targets/${targetId}/luns`, data)
    return response.data
  },

  removeLUN: async (targetId: string, lunId: string): Promise<{ message: string }> => {
    const response = await apiClient.delete(`/scst/targets/${targetId}/luns/${lunId}`)
    return response.data
  },

  addInitiator: async (targetId: string, data: AddInitiatorRequest): Promise<{ task_id: string }> => {
    const response = await apiClient.post(`/scst/targets/${targetId}/initiators`, data)
    return response.data
  },

  applyConfig: async (): Promise<{ task_id: string }> => {
    const response = await apiClient.post('/scst/config/apply')
    return response.data
  },

  listHandlers: async (): Promise<SCSTHandler[]> => {
    const response = await apiClient.get('/scst/handlers', {
      headers: {
        'Cache-Control': 'no-cache',
      },
      params: {
        _t: Date.now(),
      },
    })
    return response.data.handlers || []
  },

  listPortals: async (): Promise<SCSTPortal[]> => {
    const response = await apiClient.get('/scst/portals', {
      headers: {
        'Cache-Control': 'no-cache',
      },
      params: {
        _t: Date.now(), // Add timestamp to prevent browser caching
      },
    })
    return response.data.portals || []
  },

  getPortal: async (id: string): Promise<SCSTPortal> => {
    const response = await apiClient.get(`/scst/portals/${id}`, {
      headers: {
        'Cache-Control': 'no-cache',
      },
      params: {
        _t: Date.now(),
      },
    })
    return response.data
  },

  createPortal: async (data: { ip_address: string; port?: number; is_active?: boolean }): Promise<SCSTPortal> => {
    const response = await apiClient.post('/scst/portals', data)
    return response.data
  },

  updatePortal: async (id: string, data: { ip_address: string; port?: number; is_active?: boolean }): Promise<SCSTPortal> => {
    const response = await apiClient.put(`/scst/portals/${id}`, data)
    return response.data
  },

  deletePortal: async (id: string): Promise<void> => {
    await apiClient.delete(`/scst/portals/${id}`)
  },

  enableTarget: async (targetId: string): Promise<{ message: string }> => {
    const response = await apiClient.post(`/scst/targets/${targetId}/enable`)
    return response.data
  },

  disableTarget: async (targetId: string): Promise<{ message: string }> => {
    const response = await apiClient.post(`/scst/targets/${targetId}/disable`)
    return response.data
  },

  deleteTarget: async (targetId: string): Promise<{ message: string }> => {
    const response = await apiClient.delete(`/scst/targets/${targetId}`)
    return response.data
  },

  listInitiators: async (): Promise<SCSTInitiator[]> => {
    const response = await apiClient.get('/scst/initiators', {
      headers: {
        'Cache-Control': 'no-cache',
      },
      params: {
        _t: Date.now(),
      },
    })
    return response.data.initiators || []
  },

  getInitiator: async (id: string): Promise<SCSTInitiator> => {
    const response = await apiClient.get(`/scst/initiators/${id}`, {
      headers: {
        'Cache-Control': 'no-cache',
      },
      params: {
        _t: Date.now(),
      },
    })
    return response.data
  },

  removeInitiator: async (id: string): Promise<void> => {
    await apiClient.delete(`/scst/initiators/${id}`)
  },

  listExtents: async (): Promise<SCSTExtent[]> => {
    const response = await apiClient.get('/scst/extents', {
      headers: {
        'Cache-Control': 'no-cache',
      },
      params: {
        _t: Date.now(), // Add timestamp to prevent browser caching
      },
    })
    return response.data.extents || []
  },

  createExtent: async (extent: CreateExtentRequest): Promise<{ message: string }> => {
    const response = await apiClient.post('/scst/extents', extent)
    return response.data
  },

  deleteExtent: async (deviceName: string): Promise<void> => {
    await apiClient.delete(`/scst/extents/${deviceName}`)
  },

  // Initiator Groups
  listInitiatorGroups: async (): Promise<SCSTInitiatorGroup[]> => {
    const response = await apiClient.get('/scst/initiator-groups', {
      headers: {
        'Cache-Control': 'no-cache',
      },
      params: {
        _t: Date.now(), // Add timestamp to prevent browser caching
      },
    })
    return response.data.groups || []
  },

  getInitiatorGroup: async (id: string): Promise<SCSTInitiatorGroup> => {
    const response = await apiClient.get(`/scst/initiator-groups/${id}`, {
      headers: {
        'Cache-Control': 'no-cache',
      },
      params: {
        _t: Date.now(),
      },
    })
    return response.data
  },

  createInitiatorGroup: async (data: { target_id: string; group_name: string }): Promise<SCSTInitiatorGroup> => {
    const response = await apiClient.post('/scst/initiator-groups', data)
    return response.data
  },

  updateInitiatorGroup: async (id: string, data: { group_name: string }): Promise<SCSTInitiatorGroup> => {
    const response = await apiClient.put(`/scst/initiator-groups/${id}`, data)
    return response.data
  },

  deleteInitiatorGroup: async (id: string): Promise<void> => {
    await apiClient.delete(`/scst/initiator-groups/${id}`)
  },

  addInitiatorToGroup: async (groupId: string, initiatorIQN: string): Promise<{ message: string }> => {
    const response = await apiClient.post(`/scst/initiator-groups/${groupId}/initiators`, {
      initiator_iqn: initiatorIQN,
    })
    return response.data
  },

  // Config file management
  getConfigFile: async (path?: string): Promise<{ content: string; path: string }> => {
    const response = await apiClient.get('/scst/config/file', {
      params: path ? { path } : {},
    })
    return response.data
  },

  updateConfigFile: async (content: string, path?: string): Promise<{ message: string; path: string }> => {
    const response = await apiClient.put('/scst/config/file', {
      content,
      path,
    })
    return response.data
  },
}

export interface SCSTExtent {
  handler_type: string
  device_name: string
  device_path: string
  is_in_use: boolean
  lun_count: number
}

export interface CreateExtentRequest {
  device_name: string
  device_path: string
  handler_type: string
}

