package backend

import (
	"fmt"
)

func (a *App) AddDatabaseConfig(name string, targetPath string, modelPackagePath string) error {
	if name == "" {
		return fmt.Errorf("database name is empty")
	}
	if targetPath == "" {
		return fmt.Errorf("target path is empty")
	}

	for _, db := range a.settings.Databases {
		if db.Name == name {
			return fmt.Errorf("database with name '%s' already exists", name)
		}
	}

	a.settings.Databases = append(a.settings.Databases, DatabaseConfig{
		Name:             name,
		TargetPath:       targetPath,
		ModelPackagePath: modelPackagePath,
	})
	return a.saveSettings()
}

func (a *App) RemoveDatabaseConfig(name string) error {
	for i, db := range a.settings.Databases {
		if db.Name == name {
			a.settings.Databases = append(a.settings.Databases[:i], a.settings.Databases[i+1:]...)
			return a.saveSettings()
		}
	}
	return fmt.Errorf("database with name '%s' not found", name)
}

func (a *App) UpdateDatabaseConfig(oldName string, newName string, targetPath string, modelPackagePath string) error {
	if newName == "" {
		return fmt.Errorf("database name is empty")
	}
	if targetPath == "" {
		return fmt.Errorf("target path is empty")
	}

	for i, db := range a.settings.Databases {
		if db.Name == oldName {
			a.settings.Databases[i].Name = newName
			a.settings.Databases[i].TargetPath = targetPath
			a.settings.Databases[i].ModelPackagePath = modelPackagePath
			return a.saveSettings()
		}
	}
	return fmt.Errorf("database with name '%s' not found", oldName)
}
