package main

import (
	"fmt"
	"log"
	"os"
	"path/filepath"
	"strings"

	socketio "github.com/googollee/go-socket.io"
)

func registerBuildChannel(server *socketio.Server) {
	// Example: When clients join "build" namespace or room
	server.OnEvent("/", "subscribe:build", func(s socketio.Conn) {
		host, err := os.Hostname()
		if err != nil {
			server.BroadcastToRoom("/", "build", "buildlogs", "Could not retrieve hostname")
			return
		}

		if strings.Contains(host, "VMS") || strings.Contains(host, "vms") {
			server.BroadcastToRoom("/", "build", "buildlogs", "You are not allowed to run the build on a production server")
			return
		}

		s.Join("build")
		s.Emit("buildlogs", "👋 Connected to build channel") // this is where all the messages are actually sent to

	})

	// update channel events
	server.OnEvent("/", "build", func(s socketio.Conn, target string) {
		fmt.Println("🔨 Build triggered:", target)

		go func() {

			server.BroadcastToRoom("/", "build", "buildlogs", "🔨 Starting build: Old App")
			if err := runNpmV2Build(server); err != nil {
				server.BroadcastToRoom("/", "build", "buildlogs", fmt.Sprintf("❌ Build failed: %v", err))
				return

			}

			server.BroadcastToRoom("/", "build", "buildlogs", "🔨 Starting build: App")
			if err := runNpmBuild(server); err != nil {
				server.BroadcastToRoom("/", "build", "buildlogs", fmt.Sprintf("❌ Build failed: %v", err))
				return
			}

			server.BroadcastToRoom("/", "build", "buildlogs", "Zipping the app up")
			buildNum, err := bumpBuild()
			if err != nil {
				server.BroadcastToRoom("/", "build", "buildlogs", fmt.Sprintf("failed updating build counter, details: %v", err.Error()))
				return
			}

			// run the zip
			includes, _ := loadIncludePatterns("../.include")

			// Name the archive after build number if available
			data, _ := os.ReadFile("../.build")
			buildNum1 := strings.TrimSpace(string(data))
			if buildNum1 == "" {
				buildNum1 = "0"
			}

			buildDir, err := getBuildDir()
			if err != nil {
				log.Fatal(err)
				server.BroadcastToRoom("/", "build", "buildlogs", fmt.Sprintf("Build dir error: %v", err))
			}

			if err != nil {

				server.BroadcastToRoom("/", "build", "buildlogs", fmt.Sprintf("Build dir error: %v", err.Error()))
				return
			}

			zipPath := filepath.Join(buildDir, fmt.Sprintf("release-%d.zip", buildNum))

			if err := zipProject(server, "..", zipPath, includes); err != nil {
				server.BroadcastToRoom("/", "build", "buildlogs", fmt.Sprintf("Build zip error: %v", err.Error()))
				return
			}

			server.BroadcastToRoom("/", "build", "buildlogs", fmt.Sprintf("✅ Build finished successfully, current build: %v", buildNum))
		}()
	})
}
