package api

import (
	"fmt"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"

	"github.com/titansys/appy-builder/internal/api/middleware"
	"github.com/titansys/appy-builder/internal/client"
	"github.com/titansys/appy-builder/internal/config"
	"github.com/titansys/appy-builder/internal/models"
)

// Processor defines the interface for build queue operations
type Processor interface {
	FetchAndQueueBuilds() error
	FetchAndQueueBuildsDynamic(siteURL, purchaseCode string) error
	PendingCount() int
	ProcessingCount() int
	CompletedCount() int
	FailedCount() int
	GetBuildStatus(buildID string) (*models.BuildStatus, bool)
}

// Server represents the HTTP API server
type Server struct {
	config      *config.Config
	router      *gin.Engine
	processor   Processor
	titanClient *client.TitanClient
	logger      *logrus.Logger
	version     string
}

// NewServer creates a new API server
func NewServer(cfg *config.Config, processor Processor, titanClient *client.TitanClient, logger *logrus.Logger, version string) *Server {
	// Set Gin to release mode by default
	gin.SetMode(gin.ReleaseMode)

	router := gin.Default()

	server := &Server{
		config:      cfg,
		router:      router,
		processor:   processor,
		titanClient: titanClient,
		logger:      logger,
		version:     version,
	}

	server.setupRoutes()

	return server
}

// setupRoutes configures the API routes
func (s *Server) setupRoutes() {
	// Root endpoint (no auth required)
	s.router.GET("/", s.handleRoot)

	// Create auth middleware
	auth := middleware.NewAuthMiddleware(s.config, s.titanClient)

	// Authenticated endpoints (require server_key in path)
	s.router.POST("/trigger/:server_key", auth.ValidateServerKey(), s.handleTrigger)
	s.router.GET("/queue/:server_key", auth.ValidateServerKey(), s.handleQueue)
	s.router.GET("/download/:build_id/:server_key", auth.ValidateServerKey(), s.handleDownload)

	// Keystore generation endpoint
	s.router.POST("/keystores/generate/:server_key", auth.ValidateServerKey(), s.handleGenerateKeystore)
}

// Start starts the HTTP server
func (s *Server) Start() error {
	addr := fmt.Sprintf("%s:%d", s.config.Host, s.config.Port)
	s.logger.WithFields(logrus.Fields{
		"address": addr,
	}).Info("HTTP server starting")
	return s.router.Run(addr)
}
