import dotenv from 'dotenv';
dotenv.config();

import { createClient } from 'webdav';
import fs from 'fs';
import path from 'path';

const client = createClient(
  process.env.WEBDAV_ENDPOINT,
  {
      username: process.env.WEBDAV_USERNAME,
      password: process.env.WEBDAV_PASSWORD,
      maxBodyLength: Infinity,
      maxContentLength: Infinity,
      headers: {
          Accept: "*/*",
          Connection: "keep-alive"
      }
  }
);

async function createDirectoryIfNotExist(remotePath) {
    try {
        const exists = await client.exists(remotePath);
        if (!exists) {
            await client.createDirectory(remotePath);
        }
    } catch (error) {
        if (error.status !== 409 && error.status !== 405) {
            throw error;
        }
    }
}

async function uploadDirectory(localPath, remoteBasePath) {
    try {
        const items = fs.readdirSync(localPath, { withFileTypes: true });

        for (const item of items) {
            const localItemPath = path.join(localPath, item.name);
            const remoteItemPath = path.posix.join(remoteBasePath, item.name);

            if (item.isDirectory()) {
                // Create directory on WebDAV server
                await createDirectoryIfNotExist(remoteItemPath);
                console.log(`Verified directory: ${remoteItemPath}`);
                await uploadDirectory(localItemPath, remoteItemPath);
            } else {
                // Upload file
                console.log(`Uploading file: ${remoteItemPath}`);
                const content = fs.readFileSync(localItemPath);
                await client.putFileContents(remoteItemPath, content);
            }
        }
    } catch (error) {
        console.error(`Error processing ${localPath}:`, error.message);
        throw error;
    }
}

async function clearFolder(remotePath) {
    try {
        const items = await client.getDirectoryContents(remotePath);
        for (const item of items) {
            if (item.basename !== '..') {
                const itemPath = path.posix.join(remotePath, item.basename);
                await client.deleteFile(itemPath);
            }
        }
    } catch (error) {
        console.error('Error clearing root folder:', error.message);
        throw error;
    }
}

// Usage example
async function main() {
    const localDir = './dist';
    let remoteDir = process.env.WEBDAV_REMOTE_DIR;
    if(remoteDir === undefined) {
        remoteDir = '/';
    }

    try {
        // Clear root folder
        await clearFolder(remoteDir);

        // Upload new content
        await uploadDirectory(localDir, remoteDir);
        console.log('Directory upload complete');
    } catch (error) {
        console.error('Upload failed:', error.message);
    }
}

main();
