package log_backup

import (
	"fmt"
	"log"
	"path/filepath"

	"github.com/Vomitblood/cspj-application/server/internal/config"
	"github.com/Vomitblood/cspj-application/server/internal/webdav"
	"github.com/studio-b12/gowebdav"
)

var localLogPaths = []string{
	filepath.Join(config.LogDirectory, "host-fs-accesslog.log"),
	filepath.Join(config.LogDirectory, "host-fs-auditlog.log"),
	filepath.Join(config.LogDirectory, "host-fs-errorlog.log"),
}

var remoteFiles = []string{
	"host-fs-accesslog.log",
	"host-fs-auditlog.log",
	"host-fs-errorlog.log",
}

func BackupLogs(client *gowebdav.Client) error {
	// check if there are equal number of local and remote file paths
	if len(localLogPaths) != len(remoteFiles) {
		return fmt.Errorf("mismatch between local log paths and remote paths")
	}

	// loop through each file and upload it
	for i := range localLogPaths {
		err := webdav.UploadFile(client, localLogPaths[i], remoteFiles[i])
		if err != nil {
			log.Printf("Error uploading file %s: %v", localLogPaths[i], err)
			return fmt.Errorf("error uploading file %s: %v", localLogPaths[i], err)
		}
	}

	return nil
}

func RestoreLogs(client *gowebdav.Client) error {
	// check if there are equal number of local and remote file paths
	if len(remoteFiles) != len(localLogPaths) {
		return fmt.Errorf("mismatch between remote files and local paths")
	}

	// loop through each remote file and download it
	for i := range remoteFiles {
		err := webdav.DownloadFile(client, remoteFiles[i], localLogPaths[i])
		if err != nil {
			log.Printf("Error downloading file %s: %v", remoteFiles[i], err)
			return fmt.Errorf("error downloading file %s: %v", remoteFiles[i], err)
		}
	}

	return nil
}
