package handlers

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

	"aggios-app/backend/internal/api/middleware"
	"aggios-app/backend/internal/domain"
	"aggios-app/backend/internal/service"

	"github.com/google/uuid"
)

// CompanyHandler handles company endpoints
type CompanyHandler struct {
	companyService *service.CompanyService
}

// NewCompanyHandler creates a new company handler
func NewCompanyHandler(companyService *service.CompanyService) *CompanyHandler {
	return &CompanyHandler{
		companyService: companyService,
	}
}

// Create handles company creation
func (h *CompanyHandler) Create(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	// Get user ID from context (set by auth middleware)
	userIDStr, ok := r.Context().Value(middleware.UserIDKey).(string)
	if !ok {
		http.Error(w, "Unauthorized", http.StatusUnauthorized)
		return
	}

	userID, err := uuid.Parse(userIDStr)
	if err != nil {
		http.Error(w, "Invalid user ID", http.StatusBadRequest)
		return
	}

	var req domain.CreateCompanyRequest
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		http.Error(w, "Invalid request body", http.StatusBadRequest)
		return
	}

	// TODO: Get tenantID from user context
	// For now, this is a placeholder - you'll need to get the tenant from the authenticated user
	tenantID := uuid.New() // Replace with actual tenant from user

	company, err := h.companyService.Create(req, tenantID, userID)
	if err != nil {
		switch err {
		case service.ErrCNPJAlreadyExists:
			http.Error(w, err.Error(), http.StatusConflict)
		default:
			http.Error(w, "Internal server error", http.StatusInternalServerError)
		}
		return
	}

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

// List handles listing companies for a tenant
func (h *CompanyHandler) List(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	// TODO: Get tenantID from authenticated user
	tenantID := uuid.New() // Replace with actual tenant from user

	companies, err := h.companyService.ListByTenant(tenantID)
	if err != nil {
		http.Error(w, "Internal server error", http.StatusInternalServerError)
		return
	}

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