import * as path from 'node:path'
import * as fs from 'node:fs'

import { loadSettings, saveSettings } from './settings'

function copyOriginalData(): void {
  const settings = loadSettings()

  const originalDataPath = path.join(settings.SkyrimPath, 'Data')
  const copyDataPath = path.join(settings.SkyrimPath, 'Data_Original')

  fs.cpSync(originalDataPath, copyDataPath, { recursive: true })
  fs.rmdirSync(originalDataPath, { recursive: true })
}

function isFirstInstallation(): boolean {
  const settings = loadSettings()
  return settings.currentServer.length === 0
}

function isServerDataExists(id: string): boolean {
  const settings = loadSettings()
  return fs.existsSync(path.join(settings.SkyrimPath, `Data_${id}`))
}

function loadServerData(id: string): void {
  const settings = loadSettings()

  if (isServerDataExists(id)) {
    const dataFolder = path.join(settings.SkyrimPath, `Data_${id}`)
    fs.renameSync(dataFolder, path.join(settings.SkyrimPath, 'Data'))

    settings.currentServer = id
    saveSettings(settings)
  } else {
    // download manifest and files
  }
}

function selectServer(id: string): void {
  if (isFirstInstallation()) {
    copyOriginalData()
  }

  loadServerData(id)
}
