import prisma from "../db.server";
import { assertTenantScope } from "../lib/security/tenant-context";
import { classifyStoreCategory, type StoreCategory } from "./store-intelligence.server";

export interface StoreProfileDTO {
  shopId: string;
  category: StoreCategory;
  categoryConfidence: number;
  businessType: string;
  productTypes: string[];
  targetAudience: string;
  brandTone: string;
  currency: string;
  priceRange: { min: number; max: number };
  languages: string[];
  dominantVendors: string[];
  lastAnalyzedAt: Date;
}

export class StoreProfileService {
  /**
   * Retrieves or discovers the stable Store Profile metadata strictly scoped to shopId.
   */
  static async getStoreProfile({
    shopId,
    shopifyDomain,
  }: {
    shopId: string;
    shopifyDomain?: string;
  }): Promise<StoreProfileDTO> {
    if (!shopId) {
      throw new Error("StoreProfileService: shopId is required.");
    }

    const existing = await prisma.storeProfile.findUnique({
      where: { shopId },
    });

    if (existing) {
      assertTenantScope(existing.shopId, shopId);
      return {
        shopId: existing.shopId,
        category: existing.category as StoreCategory,
        categoryConfidence: existing.categoryConfidence,
        businessType: existing.businessType,
        productTypes: (existing.productTypes as string[]) || [],
        targetAudience: existing.targetAudience,
        brandTone: existing.brandTone,
        currency: existing.currency,
        priceRange: (existing.priceRange as any) || { min: 0, max: 0 },
        languages: (existing.languages as string[]) || ["en"],
        dominantVendors: ((existing.metadata as any)?.dominantVendors as string[]) || [],
        lastAnalyzedAt: existing.lastAnalyzedAt,
      };
    }

    // Lazy discovery if not yet cached
    const domain = shopifyDomain || (await prisma.shop.findUnique({ where: { id: shopId }, select: { shopifyDomain: true } }))?.shopifyDomain;
    if (domain) {
      const { StoreIntelligenceService } = await import("./store-intelligence.server");
      const res = await StoreIntelligenceService.analyzeStoreAndBuildProfile(shopId, domain);
      return {
        shopId: res.profile.shopId,
        category: res.profile.category,
        categoryConfidence: res.profile.categoryConfidence,
        businessType: res.profile.businessType,
        productTypes: res.profile.productTypes,
        targetAudience: res.profile.targetAudience,
        brandTone: res.profile.brandTone,
        currency: res.profile.currency,
        priceRange: res.profile.priceRange,
        languages: res.profile.languages,
        dominantVendors: (res.profile.metadata?.dominantVendors as string[]) || [],
        lastAnalyzedAt: res.profile.lastAnalyzedAt,
      };
    }

    return {
      shopId,
      category: "unknown",
      categoryConfidence: 0.0,
      businessType: "online store",
      productTypes: [],
      targetAudience: "general shoppers",
      brandTone: "helpful and polite",
      currency: "USD",
      priceRange: { min: 0, max: 0 },
      languages: ["en"],
      dominantVendors: [],
      lastAnalyzedAt: new Date(),
    };
  }
}
