import prisma from "../db.server";
import { runUniversalAIAgent } from "../lib/ai/provider";

export interface AIResponse {
  reply: string;
  intent: "product_search" | "order_status" | "general_qa" | "cart_action";
  products?: Array<{
    id: string;
    title: string;
    price: string;
    handle: string;
    url: string;
    imageUrl: string;
    variantId?: string;
  }>;
  articles?: Array<{
    id: string;
    shopifyArticleId: string;
    blogHandle: string;
    blogTitle?: string | null;
    title: string;
    handle: string;
    summary?: string | null;
    content?: string | null;
    image?: string | null;
    imageUrl?: string | null;
    author?: string | null;
    url?: string | null;
    publishedAt?: Date | string | null;
  }>;
  orderInfo?: {
    orderNumber: string;
    status: string;
    fulfillmentStatus: string;
    trackingUrl?: string;
  };
}

/**
 * Multi-Tenant AI Response Generator
 */
export async function generateAIResponse({
  userMessage,
  shop,
}: {
  userMessage: string;
  shop: string;
}): Promise<AIResponse> {
  const shopRecord = await prisma.shop.findUnique({
    where: { shopifyDomain: shop },
  });

  const shopDomain = shopRecord?.shopifyDomain || shop;
  const sessionId = `session_${Date.now()}`;

  const res = await runUniversalAIAgent({
    shopDomain,
    sessionId,
    userMessage,
  });

  return {
    reply: res.reply,
    intent: res.intent,
    products: res.products,
    articles: res.articles,
    orderInfo: res.orderInfo,
  };
}
