package handlers

import (
	"aggios-app/backend/internal/api/middleware"
	"aggios-app/backend/internal/domain"
	"aggios-app/backend/internal/repository"
	"aggios-app/backend/internal/service"
	"context"
	"encoding/json"
	"log"
	"net/http"

	"github.com/google/uuid"
	"github.com/gorilla/mux"
)

type SignupTemplateHandler struct {
	repo        *repository.SignupTemplateRepository
	userRepo    *repository.UserRepository
	tenantRepo  *repository.TenantRepository
	agencyService *service.AgencyService
}

func NewSignupTemplateHandler(
	repo *repository.SignupTemplateRepository,
	userRepo *repository.UserRepository,
	tenantRepo *repository.TenantRepository,
	agencyService *service.AgencyService,
) *SignupTemplateHandler {
	return &SignupTemplateHandler{
		repo: repo,
		userRepo: userRepo,
		tenantRepo: tenantRepo,
		agencyService: agencyService,
	}
}

// CreateTemplate cria um novo template (SuperAdmin)
func (h *SignupTemplateHandler) CreateTemplate(w http.ResponseWriter, r *http.Request) {
	var template domain.SignupTemplate
	if err := json.NewDecoder(r.Body).Decode(&template); err != nil {
		log.Printf("Error decoding request body: %v", err)
		http.Error(w, "Invalid request body", http.StatusBadRequest)
		return
	}

	// Pegar user_id do contexto (do middleware de autenticação)
	userIDStr, ok := r.Context().Value(middleware.UserIDKey).(string)
	if !ok || userIDStr == "" {
		http.Error(w, "Unauthorized", http.StatusUnauthorized)
		return
	}

	userID, err := uuid.Parse(userIDStr)
	if err != nil {
		log.Printf("Error parsing user_id: %v", err)
		http.Error(w, "Invalid user ID", http.StatusUnauthorized)
		return
	}

	template.CreatedBy = userID
	template.IsActive = true

	ctx := context.Background()
	if err := h.repo.Create(ctx, &template); err != nil {
		log.Printf("Error creating signup template: %v", err)
		http.Error(w, "Error creating template", http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusCreated)
	json.NewEncoder(w).Encode(template)
}

// ListTemplates lista todos os templates (SuperAdmin)
func (h *SignupTemplateHandler) ListTemplates(w http.ResponseWriter, r *http.Request) {
	ctx := context.Background()
	templates, err := h.repo.List(ctx)
	if err != nil {
		log.Printf("Error listing signup templates: %v", err)
		http.Error(w, "Error listing templates", http.StatusInternalServerError)
		return
	}

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

// GetTemplateBySlug retorna um template pelo slug (público)
func (h *SignupTemplateHandler) GetTemplateBySlug(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	slug := vars["slug"]

	ctx := context.Background()
	template, err := h.repo.FindBySlug(ctx, slug)
	if err != nil {
		log.Printf("Error finding signup template by slug %s: %v", slug, err)
		http.Error(w, "Template not found", http.StatusNotFound)
		return
	}

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

// GetTemplateByID retorna um template pelo ID (SuperAdmin)
func (h *SignupTemplateHandler) GetTemplateByID(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	idStr := vars["id"]

	id, err := uuid.Parse(idStr)
	if err != nil {
		http.Error(w, "Invalid template ID", http.StatusBadRequest)
		return
	}

	ctx := context.Background()
	template, err := h.repo.FindByID(ctx, id)
	if err != nil {
		log.Printf("Error finding signup template by ID %s: %v", idStr, err)
		http.Error(w, "Template not found", http.StatusNotFound)
		return
	}

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

// UpdateTemplate atualiza um template (SuperAdmin)
func (h *SignupTemplateHandler) UpdateTemplate(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	idStr := vars["id"]

	id, err := uuid.Parse(idStr)
	if err != nil {
		http.Error(w, "Invalid template ID", http.StatusBadRequest)
		return
	}

	var template domain.SignupTemplate
	if err := json.NewDecoder(r.Body).Decode(&template); err != nil {
		log.Printf("Error decoding request body: %v", err)
		http.Error(w, "Invalid request body", http.StatusBadRequest)
		return
	}

	template.ID = id

	ctx := context.Background()
	if err := h.repo.Update(ctx, &template); err != nil {
		log.Printf("Error updating signup template: %v", err)
		http.Error(w, "Error updating template", http.StatusInternalServerError)
		return
	}

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

// DeleteTemplate deleta um template (SuperAdmin)
func (h *SignupTemplateHandler) DeleteTemplate(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	idStr := vars["id"]

	id, err := uuid.Parse(idStr)
	if err != nil {
		http.Error(w, "Invalid template ID", http.StatusBadRequest)
		return
	}

	ctx := context.Background()
	if err := h.repo.Delete(ctx, id); err != nil {
		log.Printf("Error deleting signup template: %v", err)
		http.Error(w, "Error deleting template", http.StatusInternalServerError)
		return
	}

	w.WriteHeader(http.StatusNoContent)
}
