import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { mount, flushPromises } from '@vue/test-utils'
import { createPinia, setActivePinia } from 'pinia'

// Use connection UUID, never provider slug
const mockPush = vi.fn()
const mockReplace = vi.fn()

vi.mock('vue-router', () => ({
  useRouter: () => ({ push: mockPush, replace: mockReplace }),
  useRoute: () => ({
    params: { connectionId: 'uuid-conn-1', folderId: 'root' },
    query: {},
  }),
}))

const mockFetchConnections = vi.fn().mockResolvedValue(undefined)
const mockSelectConnection = vi.fn()
const mockSetBrowseState = vi.fn()

vi.mock('../../stores/cloudConnections.js', () => ({
  useCloudConnectionsStore: () => ({
    connections: [{ id: 'uuid-conn-1', provider: 'google_drive', display_name: 'My Drive' }],
    loading: false,
    capabilities: null,
    folderFreshness: null,
    lastRefreshedAt: null,
    byteAvailability: null,
    fetchConnections: mockFetchConnections,
    selectConnection: mockSelectConnection,
    setBrowseState: mockSetBrowseState,
    defaultDisplayName: (c) => c.provider,
  }),
  saveLastFolder: vi.fn(),
  loadLastFolder: vi.fn(() => null),
}))

vi.mock('../../api/client.js', () => ({
  getCloudFoldersByConnectionId: vi.fn().mockResolvedValue({ items: [], capabilities: null }),
  uploadToCloud: vi.fn(),
  listCloudConnections: vi.fn().mockResolvedValue({ items: [] }),
}))

vi.mock('../../stores/toast.js', () => ({
  useToastStore: () => ({ show: vi.fn() }),
}))

import CloudFolderView from '../CloudFolderView.vue'
import * as api from '../../api/client.js'

const globalStubs = {
  StorageBrowser: {
    template: '<div data-test="storage-browser" />',
    props: [
      'mode', 'folders', 'files', 'breadcrumb', 'uploadQueue', 'loading',
      'emptyMessage', 'emptyHint', 'capabilities', 'connectionRoot',
      'folderFreshness', 'lastRefreshedAt', 'byteAvailability',
    ],
    emits: ['breadcrumb-navigate', 'upload', 'folder-navigate', 'file-open'],
  },
}

beforeEach(() => {
  setActivePinia(createPinia())
  vi.clearAllMocks()
  sessionStorage.clear()
})

afterEach(() => {
  sessionStorage.clear()
})

describe('CloudFolderView', () => {
  it('calls getCloudFoldersByConnectionId with connection UUID, never provider slug', async () => {
    const w = mount(CloudFolderView, { global: { stubs: globalStubs } })
    await flushPromises()
    expect(api.getCloudFoldersByConnectionId).toHaveBeenCalledWith('uuid-conn-1', 'root')
    // Never called with provider slug
    expect(api.getCloudFoldersByConnectionId).not.toHaveBeenCalledWith('google_drive', expect.anything())
  })

  it('renders StorageBrowser (no parallel file grid)', () => {
    const w = mount(CloudFolderView, { global: { stubs: globalStubs } })
    expect(w.find('[data-test="storage-browser"]').exists()).toBe(true)
    // No grid markup in view itself
    expect(w.findAll('table').length).toBe(0)
  })

  it('passes connectionId to store selectConnection', async () => {
    const w = mount(CloudFolderView, { global: { stubs: globalStubs } })
    await flushPromises()
    expect(mockSelectConnection).toHaveBeenCalledWith('uuid-conn-1')
  })

  it('fresh session at root does not redirect when no stored folder', async () => {
    const w = mount(CloudFolderView, { global: { stubs: globalStubs } })
    await flushPromises()
    expect(mockReplace).not.toHaveBeenCalled()
  })
})
