package commands

import (
	"context"
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"
	"strings"

	"git.jabali-panel.com/shukivaknin/jabali2/agentwire"
)

type joomlaDeleteReq struct {
	AppType      string `json:"app_type"`     // present, ignored
	OSUser       string `json:"os_user"`
	Docroot      string `json:"docroot"`
	Subdirectory string `json:"subdirectory,omitempty"`
	Domain       string `json:"domain,omitempty"`
}

type joomlaDeleteResp struct {
	Status string `json:"status"`
}

// joomlaTopLevel lists every entry the upstream Joomla 5 tarball lays
// down at the install root. Generated from Joomla 5.2.0; bump if a
// future release adds a top-level entry. Entries that don't exist on
// disk are skipped silently.
//
// configuration.php is generated by the CLI installer; installation/
// is removed immediately after install but listed here in case a
// failed install left a partial copy behind.
var joomlaTopLevel = []string{
	".htaccess",
	"administrator",
	"api",
	"cache",
	"cli",
	"components",
	"configuration.php",
	"htaccess.txt",
	"images",
	"includes",
	"index.php",
	"installation",
	"language",
	"layouts",
	"libraries",
	"LICENSE.txt",
	"media",
	"modules",
	"plugins",
	"README.txt",
	"robots.txt",
	"robots.txt.dist",
	"templates",
	"tmp",
	"web.config.txt",
}

func joomlaDeleteHandler(ctx context.Context, params json.RawMessage) (any, error) {
	var req joomlaDeleteReq
	if err := json.Unmarshal(params, &req); err != nil {
		return nil, &agentwire.AgentError{Code: agentwire.CodeInvalidArgument, Message: fmt.Sprintf("failed to parse params: %v", err)}
	}
	if req.OSUser == "" {
		return nil, &agentwire.AgentError{Code: agentwire.CodeInvalidArgument, Message: "os_user is required"}
	}
	if req.Docroot == "" {
		return nil, &agentwire.AgentError{Code: agentwire.CodeInvalidArgument, Message: "docroot is required"}
	}
	if err := validateDocrootPath(req.OSUser, req.Docroot); err != nil {
		return nil, &agentwire.AgentError{Code: agentwire.CodeInvalidArgument, Message: fmt.Sprintf("invalid docroot: %v", err)}
	}

	installPath := computeJoomlaInstallPath(req.Docroot, req.Subdirectory)

	if req.Subdirectory != "" {
		cmd := buildSystemdRunCmd(ctx, req.OSUser, "rm", "-rf", installPath)
		_ = cmd.Run()
	} else {
		for _, name := range joomlaTopLevel {
			cmd := buildSystemdRunCmd(ctx, req.OSUser, "rm", "-rf", filepath.Join(installPath, name))
			_ = cmd.Run()
		}
	}

	if req.Subdirectory == "" && req.Domain != "" {
		indexPath := filepath.Join(req.Docroot, "index.html")
		if _, err := os.Stat(indexPath); os.IsNotExist(err) {
			_ = writeDefaultIndex(ctx, indexPath, req.OSUser, req.Domain, req.Docroot, "")
		}
	}

	// Remove the per-install nginx rewrite snippet if one was written
	// at install time. No-op for docroot installs.
	if sub := strings.Trim(req.Subdirectory, "/"); sub != "" && req.Domain != "" {
		_ = removeAppRewrite(ctx, "joomla", req.Domain, sub)
	}

	return joomlaDeleteResp{Status: "deleted"}, nil
}

func init() {
	RegisterAppDeleter("joomla", joomlaDeleteHandler)
}
