// NKSC1-c8c7ea42327292095dea8150adbebc85-0708f3a4174e426d0d2ad28718b26adb4894e3d58893d8e7340ae63a514fbf41

package handlers

import (
	"github.com/gin-gonic/gin"
	"wa-assistant/backend/database"
	"wa-assistant/backend/models"
)

// A long-lived stream must stop after an account or assignment is revoked,
// even if the browser keeps its original authenticated connection open.
func mayContinueInboxStream(c *gin.Context, agentID uint) bool {
	return mayContinueInboxStreams(c, []uint{agentID})
}

func mayContinueInboxStreams(c *gin.Context, agentIDs []uint) bool {
	if isTenantAdmin(c) {
		return true
	}
	var count int64
	err := database.DB.Model(&models.User{}).
		Joins("JOIN user_agent_assignments uaa ON uaa.user_id = users.id AND uaa.tenant_id = users.tenant_id").
		Joins("JOIN agents a ON a.id = uaa.agent_id AND a.tenant_id = uaa.tenant_id").
		Where("users.id = ? AND users.active = ? AND users.tenant_id = ? AND a.id IN ?", currentUserID(c), true, currentTenantID(c), agentIDs).
		Distinct("a.id").
		Count(&count).Error
	return err == nil && count == int64(len(agentIDs))
}

func workspacePermissions(c *gin.Context) models.WorkspacePermissions {
	if isTenantAdmin(c) {
		return models.WorkspacePermissions{Connect: true, ManageAI: true}
	}
	return models.WorkspacePermissions{Connect: c.GetBool("can_connect"), ManageAI: c.GetBool("can_manage_ai")}
}

// Exact routes prevent broad access to credentials, campaigns or team management.
func allowedWorkspaceRoute(c *gin.Context) bool {
	p := workspacePermissions(c)
	route := c.Request.Method + " " + c.FullPath()
	if p.Connect {
		switch route {
		case "POST /api/agents/:id/wa/connect", "POST /api/agents/:id/wa/connect-pairing", "POST /api/agents/:id/wa/logout":
			return true
		}
	}
	if !p.ManageAI {
		return false
	}
	switch route {
	case "PUT /api/agents/:id",
		"POST /api/agents/:id/setup-wizard",
		"GET /api/agents/:id/knowledge", "POST /api/agents/:id/knowledge",
		"POST /api/agents/:id/knowledge/generate", "POST /api/agents/:id/knowledge/import",
		"POST /api/agents/:id/knowledge/pdf", "GET /api/agents/:id/ai-readiness",
		"POST /api/agents/:id/knowledge/bulk-delete",
		"POST /api/agents/:id/knowledge/bulk-review",
		"POST /api/agents/:id/knowledge/reindex",
		"PUT /api/agents/:id/knowledge/:kid", "DELETE /api/agents/:id/knowledge/:kid",
		"POST /api/agents/:id/knowledge/:kid/review", "DELETE /api/agents/:id/knowledge-all",
		"GET /api/agents/:id/knowledge-usage",
		"POST /api/agents/:id/crawl", "GET /api/agents/:id/crawl", "GET /api/agents/:id/crawl/:jobId",
		"POST /api/agents/:id/crawl/:jobId/train", "POST /api/agents/:id/crawl/:jobId/train/stop",
		"POST /api/agents/:id/persona/regenerate",
		"POST /api/agents/:id/test-chat", "GET /api/agents/:id/test-chat/logs/:turnID",
		"POST /api/agents/:id/test-chat/logs/:turnID/feedback",
		"GET /api/agents/:id/test-chat/logs/:turnID/events", "POST /api/agents/:id/test-chat/logs/:turnID/correction",
		"GET /api/agents/:id/ai-forms", "POST /api/agents/:id/ai-forms",
		"PUT /api/agents/:id/ai-forms/:fid", "DELETE /api/agents/:id/ai-forms/:fid",
		"GET /api/agents/:id/ai-form-submissions",
		"GET /api/agents/:id/follow-up-notifications", "PUT /api/agents/:id/follow-up-notifications",
		"GET /api/agents/:id/handoff-notifications", "PUT /api/agents/:id/handoff-notifications":
		return true
	}
	return false
}
