package handlers

import (
	"fmt"
	"net/http"
	"time"
	"whatsapp-bot/db"
	"whatsapp-bot/services"

	"github.com/gin-gonic/gin"
)

// NOTA: Borramos la definición local de WebhookPayload porque ahora la importamos de services

func VerifyWebhook(c *gin.Context) {
	mode := c.Query("hub.mode")
	token := c.Query("hub.verify_token")
	challenge := c.Query("hub.challenge")

	if mode == "subscribe" && token == "YOUR_SECRET_TOKEN" {
		c.String(http.StatusOK, challenge)
	} else {
		c.Status(http.StatusForbidden)
	}
}

func HandleMessage(c *gin.Context) {
	// Ahora usamos services.WebhookPayload sin problemas
	var payload services.WebhookPayload
	if err := c.BindJSON(&payload); err != nil {
		c.Status(200)
		return
	}

	for _, entry := range payload.Entry {
		for _, change := range entry.Changes {
			// 1. IDENTIFICAR AL USUARIO
			phoneID := change.Value.Metadata.PhoneNumberID

			botConfig, err := db.GetBotByPhoneID(phoneID)
			if err != nil {
				fmt.Printf("❌ Unknown Phone ID: %s. Make sure this ID is in bot_configs table.\n", phoneID)
				continue
			}

			for _, msg := range change.Value.Messages {
				if msg.Type != "text" {
					continue
				}

				fmt.Printf("📩 Msg for User %d (%s): %s\n", botConfig.UserID, botConfig.PhoneID, msg.Text.Body)

				// 2. CONSTRUIR PROMPT
				currentTime := time.Now().Format("Monday, 2006-01-02 15:04")
				finalPrompt := fmt.Sprintf(
					"%s\n\nCONTEXT:\nCurrent Time: %s\nAvailability Rules: %s\n\nINSTRUCTIONS:\nIf booking, ask for Name, Date, Time. Use 'create_appointment' tool only when confirmed.",
					botConfig.SystemPrompt,
					currentTime,
					botConfig.Availability,
				)

				// 3. LLAMAR A LA IA
				aiResp, _ := services.StreamAIResponse(botConfig.UserID, msg.Text.Body, finalPrompt, nil)

				// 4. RESPONDER
				if aiResp != "" {
					services.SendWhatsAppMessage(botConfig.Token, botConfig.PhoneID, msg.From, aiResp)
				}
			}
		}
	}
	c.Status(200)
}
