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

export interface ThemeContextDTO {
  shopId: string;
  themeName: string;
  visualStyle: string;
  navigationCategories: string[];
  featuredCollections: string[];
  brandPresentation?: string | null;
  storefrontLanguage: string;
  lastAnalyzedAt: Date;
}

export class ThemeContextService {
  /**
   * Retrieves presentation/theme context strictly scoped to shopId.
   * NOTE: Theme information is presentation context ONLY and never authoritative for product specs.
   */
  static async getThemeContext({
    shopId,
    shopifyDomain,
  }: {
    shopId: string;
    shopifyDomain?: string;
  }): Promise<ThemeContextDTO> {
    if (!shopId) {
      throw new Error("ThemeContextService: shopId is required.");
    }

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

    if (existing) {
      assertTenantScope(existing.shopId, shopId);
      return {
        shopId: existing.shopId,
        themeName: existing.themeName || "Shopify Storefront",
        visualStyle: existing.visualStyle || "clean responsive e-commerce",
        navigationCategories: (existing.navigationCategories as string[]) || [],
        featuredCollections: (existing.featuredCollections as string[]) || [],
        brandPresentation: existing.brandPresentation,
        storefrontLanguage: existing.storefrontLanguage || "en",
        lastAnalyzedAt: existing.lastAnalyzedAt,
      };
    }

    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.theme.shopId,
        themeName: res.theme.themeName || "Shopify Storefront",
        visualStyle: res.theme.visualStyle || "clean responsive e-commerce",
        navigationCategories: res.theme.navigationCategories,
        featuredCollections: res.theme.featuredCollections,
        brandPresentation: res.theme.brandPresentation,
        storefrontLanguage: res.theme.storefrontLanguage,
        lastAnalyzedAt: res.theme.lastAnalyzedAt,
      };
    }

    return {
      shopId,
      themeName: "Shopify Storefront",
      visualStyle: "clean responsive e-commerce",
      navigationCategories: ["All Products"],
      featuredCollections: ["Featured Items"],
      brandPresentation: null,
      storefrontLanguage: "en",
      lastAnalyzedAt: new Date(),
    };
  }
}
