package webdav

import (
	"fmt"
	"log"
	"os"

	"github.com/studio-b12/gowebdav"
)

type WebDAVClient struct {
	Client *gowebdav.Client
}

const (
	// TODO: use values from config file
	webdavURL      = "https://webdav.vomitblood.com"
	webdavUser     = "vomitblood"
	webdavPassword = "alpine"
)

func Init() *gowebdav.Client {
	// initialize the webdav client
	client := gowebdav.NewClient(webdavURL, webdavUser, webdavPassword)

	// establish a connection to the webdav server
	err := client.Connect()
	if err != nil {
		log.Fatalf("Failed to connect to WebDAV server: %v", err)
	}

	log.Println("Connected to WebDAV server")
	return client
}

func CreateDirectory(client *gowebdav.Client, remoteDir string) error {
	err := client.Mkdir(remoteDir, 0755)
	if err != nil {
		return fmt.Errorf("failed to create directory %s: %v", remoteDir, err)
	}
	log.Printf("Created directory: %s", remoteDir)
	return nil
}

func UploadFile(client *gowebdav.Client, localFilePath string, remoteFilePath string) error {
	bytes, err := os.ReadFile(localFilePath)
	if err != nil {
		return fmt.Errorf("failed to read file %s: %v", localFilePath, err)
	}

	err = client.Write(remoteFilePath, bytes, 0777)
	if err != nil {
		return fmt.Errorf("failed to upload file %s: %v", localFilePath, err)
	}

	log.Printf("Uploaded file: %s to %s", localFilePath, remoteFilePath)
	return nil
}

func DownloadFile(client *gowebdav.Client, remoteFilePath string, localFilePath string) error {
	bytes, err := client.Read(remoteFilePath)
	if err != nil {
		return fmt.Errorf("failed to download file %s: %v", remoteFilePath, err)
	}

	err = os.WriteFile(localFilePath, bytes, 0777)
	if err != nil {
		return fmt.Errorf("failed to save downloaded file %s: %v", localFilePath, err)
	}

	log.Printf("Downloaded file: %s to %s", remoteFilePath, localFilePath)
	return nil
}
