/**
 * Workflows MCP Server
 *
 * Efficient data operations for workflow management.
 * Returns summary data instead of full records to minimize token usage.
 */

import { prisma } from "@/lib/db";

/**
 * Tier-based workflow access control
 */
const WORKFLOW_TIER_MAP: Record<string, string[]> = {
  starter: ["ai_agent", "whatsapp"],
  professional: ["ai_agent", "whatsapp", "quotations", "voice_agent"],
  enterprise: [
    "ai_agent",
    "whatsapp",
    "quotations",
    "voice_agent",
    "social_media",
    "crm_integration",
  ],
};

/**
 * Get workflows for a user with tier-based filtering
 */
export async function getUserWorkflows(userId: string, tier: string) {
  const allowedWorkflows = getAllowedWorkflowsByTier(tier);

  const workflows = await prisma.userWorkflow.findMany({
    where: {
      userId,
      workflowType: { in: allowedWorkflows },
    },
    select: {
      id: true,
      workflowType: true,
      status: true,
      lastRunAt: true,
      lastRunStatus: true,
      createdAt: true,
    },
    orderBy: { createdAt: "desc" },
  });

  return workflows;
}

/**
 * Get workflow summary counts for dashboard
 */
export async function getWorkflowSummary(userId: string) {
  const workflows = await prisma.userWorkflow.findMany({
    where: { userId },
    select: {
      workflowType: true,
      status: true,
    },
  });

  const summary = {
    total: workflows.length,
    active: workflows.filter((w) => w.status === "active").length,
    inactive: workflows.filter((w) => w.status === "inactive").length,
    error: workflows.filter((w) => w.status === "error").length,
    byType: workflows.reduce(
      (acc, w) => {
        acc[w.workflowType] = (acc[w.workflowType] || 0) + 1;
        return acc;
      },
      {} as Record<string, number>,
    ),
  };

  return summary;
}

/**
 * Get allowed workflow types for a given tier
 */
export function getAllowedWorkflowsByTier(tier: string): string[] {
  const normalizedTier = tier.toLowerCase();
  return WORKFLOW_TIER_MAP[normalizedTier] || WORKFLOW_TIER_MAP.starter;
}

/**
 * Check if a tier can access a specific workflow type
 */
export function canAccessWorkflow(tier: string, workflowType: string): boolean {
  const allowedWorkflows = getAllowedWorkflowsByTier(tier);
  return allowedWorkflows.includes(workflowType);
}

/**
 * Get workflow status counts by type
 */
export async function getWorkflowStatusByType(
  userId: string,
  workflowType: string,
) {
  const workflow = await prisma.userWorkflow.findFirst({
    where: { userId, workflowType },
    select: {
      status: true,
      lastRunAt: true,
      lastRunStatus: true,
    },
  });

  return workflow || null;
}

/**
 * Get all workflow types with their status
 */
export async function getAllWorkflowsWithStatus(userId: string, tier: string) {
  const allowedWorkflows = getAllowedWorkflowsByTier(tier);
  const userWorkflows = await prisma.userWorkflow.findMany({
    where: { userId, workflowType: { in: allowedWorkflows } },
    select: {
      workflowType: true,
      status: true,
      lastRunAt: true,
    },
  });

  // Create map of existing workflows
  const workflowMap = userWorkflows.reduce(
    (acc, w) => {
      acc[w.workflowType] = {
        status: w.status,
        lastRunAt: w.lastRunAt,
      };
      return acc;
    },
    {} as Record<string, any>,
  );

  // Return all allowed workflows with their status
  return allowedWorkflows.map((type) => ({
    workflowType: type,
    status: workflowMap[type]?.status || "inactive",
    lastRunAt: workflowMap[type]?.lastRunAt || null,
    isAvailable: true,
  }));
}
