import { defineStore } from 'pinia'
import { ref } from 'vue'
import apiClient from '../api/client'
import { useAuthStore } from './auth'

export const useFilesStore = defineStore('files', () => {
  const files = ref([])
  const breadcrumb = ref([])
  const currentParentId = ref(null)
  const loading = ref(false)

  async function loadFiles(parentId = null) {
    loading.value = true
    try {
      currentParentId.value = parentId
      const params = parentId ? { parent_id: parentId } : {}
      const response = await apiClient.get('/files', { params })
      files.value = response.data.files
      breadcrumb.value = response.data.breadcrumb
    } finally {
      loading.value = false
    }
  }

  async function createFolder(name, parentId = null) {
    const response = await apiClient.post('/files/folder', {
      name,
      parent_id: parentId,
    })
    await loadFiles(parentId)
    return response.data
  }

  async function uploadFile(file, parentId = null) {
    const formData = new FormData()
    formData.append('file', file)
    if (parentId) formData.append('parent_id', parentId)

    const response = await apiClient.post('/files/upload', formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
    })
    await loadFiles(parentId)
    return response.data
  }

  async function deleteFile(fileId) {
    await apiClient.delete(`/files/${fileId}`)
    await loadFiles(currentParentId.value)
  }

  async function renameFile(fileId, newName) {
    await apiClient.put(`/files/${fileId}`, { name: newName })
    await loadFiles(currentParentId.value)
  }

  async function moveFile(fileId, newParentId) {
    await apiClient.put(`/files/${fileId}`, { parent_id: newParentId })
    await loadFiles(currentParentId.value)
  }

  async function createShareLink(fileId, options = {}) {
    const response = await apiClient.post(`/files/${fileId}/share`, options)
    return response.data
  }

  async function getShareLinks(fileId) {
    const response = await apiClient.get(`/files/${fileId}/shares`)
    return response.data
  }

  async function deleteShareLink(token) {
    await apiClient.delete(`/share/${token}`)
  }

  function downloadUrl(fileId) {
    const auth = useAuthStore()
    return `/api/files/${fileId}/download?token=${encodeURIComponent(auth.accessToken || '')}`
  }

  return {
    files, breadcrumb, currentParentId, loading,
    loadFiles, createFolder, uploadFile, deleteFile,
    renameFile, moveFile, createShareLink, getShareLinks,
    deleteShareLink, downloadUrl,
  }
})
