package backend

import (
	"fmt"
	"os"
	"path/filepath"
)

func (a *App) AddProjectConfig(name string, path string) error {
	if path == "" {
		return fmt.Errorf("project path is empty")
	}

	if name == "" {
		name = filepath.Base(path)
	}

	goModPath := filepath.Join(path, "go.mod")
	if _, err := os.Stat(goModPath); err != nil {
		if os.IsNotExist(err) {
			return fmt.Errorf("go.mod file not found in the specified path")
		}
		return fmt.Errorf("error checking go.mod file: %w", err)
	}

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

	a.settings.Projects = append(a.settings.Projects, ProjectConfig{
		Name: name,
		Path: path,
	})
	return a.saveSettings()
}

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

func (a *App) UpdateProjectConfig(oldName string, newName string, path string) error {
	if newName == "" {
		return fmt.Errorf("project name is empty")
	}
	if path == "" {
		return fmt.Errorf("project path is empty")
	}

	goModPath := filepath.Join(path, "go.mod")
	if _, err := os.Stat(goModPath); err != nil {
		if os.IsNotExist(err) {
			return fmt.Errorf("go.mod file not found in the specified path")
		}
		return fmt.Errorf("error checking go.mod file: %w", err)
	}

	for i, project := range a.settings.Projects {
		if project.Name == oldName {
			a.settings.Projects[i].Name = newName
			a.settings.Projects[i].Path = path
			return a.saveSettings()
		}
	}
	return fmt.Errorf("project with name '%s' not found", oldName)
}
