import prisma from "../db.server";
import { assertTenantScope } from "../lib/security/tenant-context";

export interface RetrievedPolicyDTO {
  id: string;
  shopId: string;
  type: string;
  title: string;
  content: string;
}

export interface PolicyRetrievalResult {
  shopId: string;
  policies: RetrievedPolicyDTO[];
}

export class PolicyRetrievalService {
  /**
   * Authoritative store policy, FAQ, and knowledge-base retrieval strictly scoped to shopId.
   */
  static async getRelevantPoliciesAndKnowledge({
    shopId,
    query,
    intent,
  }: {
    shopId: string;
    query?: string;
    intent?: string;
  }): Promise<PolicyRetrievalResult> {
    if (!shopId) {
      throw new Error("PolicyRetrievalService: shopId is required.");
    }

    const trimmedQuery = (query || "").trim().toLowerCase();
    const whereClause: any = { shopId, enabled: true };

    if (trimmedQuery.length > 0) {
      const orConditions: any[] = [
        { title: { contains: trimmedQuery } },
        { content: { contains: trimmedQuery } },
        { sourceType: { contains: trimmedQuery } },
      ];

      // Stemming / aliases for common customer policy inquiries
      if (trimmedQuery.includes("ship") || trimmedQuery.includes("delivery") || trimmedQuery.includes("track")) {
        orConditions.push({ sourceType: { contains: "shipping" } }, { title: { contains: "shipping" } }, { title: { contains: "delivery" } });
      }
      if (trimmedQuery.includes("return") || trimmedQuery.includes("refund") || trimmedQuery.includes("exchange")) {
        orConditions.push({ sourceType: { contains: "return" } }, { title: { contains: "return" } }, { title: { contains: "refund" } });
      }

      whereClause.OR = orConditions;
    }

    const records = await prisma.knowledgeBase.findMany({
      where: whereClause,
      take: 6,
      orderBy: { createdAt: "desc" },
    });

    records.forEach((r) => assertTenantScope(r.shopId, shopId));

    const policies: RetrievedPolicyDTO[] = records.map((r) => ({
      id: r.id,
      shopId: r.shopId,
      type: r.sourceType,
      title: r.title,
      content: r.content,
    }));

    return {
      shopId,
      policies,
    };
  }
}
