package handler

import (
	"encoding/json"
	"log"
	"net/http"

	"github.com/google/uuid"
	"github.com/zs/InsightReply/internal/model"
	"github.com/zs/InsightReply/internal/repository"
)

type ReplyHandler struct {
	repo *repository.ReplyRepository
}

func NewReplyHandler(repo *repository.ReplyRepository) *ReplyHandler {
	return &ReplyHandler{repo: repo}
}

func (h *ReplyHandler) RecordReply(w http.ResponseWriter, r *http.Request) {
	var body struct {
		TweetID      string `json:"tweet_id"`
		StrategyType string `json:"strategy_type"`
		Content      string `json:"content"`
		Language     string `json:"language"`
	}

	if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
		SendError(w, http.StatusBadRequest, 4001, "Invalid request body")
		return
	}

	ctx := r.Context()
	userID, ok := ctx.Value("userID").(string)
	if !ok || userID == "" {
		SendError(w, http.StatusUnauthorized, 4002, "Unauthorized")
		return
	}

	userUUID, err := uuid.Parse(userID)
	if err != nil {
		SendError(w, http.StatusBadRequest, 4003, "Invalid user ID format")
		return
	}

	// Resolve the raw string X_Tweet_ID into our internal UUID
	// Create a dummy tweet entry via Upsert if it doesn't exist yet so foreign keys don't panic
	tweet := &model.Tweet{
		XTweetID:    body.TweetID,
		Content:     body.Content, // Temporarily store AI content as a placeholder if original is missing
		IsProcessed: false,
	}
	
	err = h.repo.UpsertDummyTweet(tweet)
	if err != nil {
		SendError(w, http.StatusInternalServerError, 5001, "Failed to resolve tweet reference")
		return
	}

	reply := &model.GeneratedReply{
		UserID:       userUUID,
		TweetID:      tweet.ID,
		StrategyType: body.StrategyType,
		Content:      body.Content,
		Status:       "copied",
		Language:     body.Language,
	}

	if err := h.repo.CreateGeneratedReply(reply); err != nil {
		SendError(w, http.StatusInternalServerError, 5002, "Failed to log generated reply")
		return
	}

	SendSuccess(w, map[string]string{		"message": "Reply recorded successfully",
	})
}

// GetReplies handles GET /api/v1/replies
func (h *ReplyHandler) GetReplies(w http.ResponseWriter, r *http.Request) {
	userIDStr := r.Header.Get("X-User-ID")
	userID, err := uuid.Parse(userIDStr)
	if err != nil {
		http.Error(w, "Unauthorized", http.StatusUnauthorized)
		return
	}

	replies, err := h.repo.GetGeneratedRepliesByUser(userID)
	if err != nil {
		log.Printf("Failed to get replies: %v", err)
		http.Error(w, "Failed to get replies", http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(replies)
}
