import type { AxiosResponse } from 'axios'
import type { BglFile, BglFilePatch, UploadOptions } from './upload.types.d.ts'
import axios from 'axios'

export const files = {
	setBaseUrl: (baseUrl?: string) => {
		if (!baseUrl) return
		baseUrl = baseUrl.replace(/\/$/, '')
		axios.defaults.baseURL = baseUrl
	},

	get: async (pathKey?: string): Promise<AxiosResponse<BglFile>> => { return axios.get('/files_v2/', { params: { path_key: pathKey } }) },

	put: async (bglFilePatch: BglFilePatch, pathKey?: string): Promise<AxiosResponse<BglFile>> => { return axios.put('/files_v2/', bglFilePatch, { params: { path_key: pathKey } }) },

	delete: async (pathKey?: string) => { return axios.delete('/files_v2/', { params: { path_key: pathKey } }) },

	upload: async (file: File, options?: UploadOptions & { dirPath?: string, tags?: string[] }): Promise<AxiosResponse<BglFile>> => {
		const formData = new FormData()
		formData.append('upload', file)
		return axios.post('/files_v2/upload', formData, {
			headers: { 'Content-Type': 'multipart/form-data' },

			onUploadProgress: options?.onUploadProgress,
			params: { dir_path: options?.dirPath, tags: options?.tags },

		}) },

	list: async (dirPath?: string): Promise<AxiosResponse<BglFile[]>> => {
		return axios.get('/files_v2/list', { params: { dir_path: dirPath } })
	}
}
