import type { PlanTier } from "@prisma/client";

export type FeatureKey =
  | "shopify.products"
  | "shopify.cart"
  | "shopify.checkout"
  | "shopify.customer_auth"
  | "openai"
  | "ai.chatbot"
  | "ai.recommendations"
  | "ai.support";

export type BillingType = "ONE_TIME" | "RECURRING";
export type BillingIntervalType = "ONE_TIME" | "MONTHLY" | "ANNUAL";

export interface PlanDetails {
  name: PlanTier;
  displayName: string;
  price: number;
  billingType: BillingType;
  billingInterval: BillingIntervalType;
  aiUsageEnabled: boolean;
  aiMonthlyLimit: number | null; // null for all plans (no artificial quota; BYOK)
  monthlyLimit: number; // 0 (unlimited via merchant's own API key)
  description: string;
  featureFlags: Record<FeatureKey, boolean>;
  features: string[];
}

export const PLAN_CONFIGS: Record<PlanTier, PlanDetails> = {
  FREE: {
    name: "FREE",
    displayName: "Free",
    price: 0.0,
    billingType: "RECURRING",
    billingInterval: "MONTHLY",
    aiUsageEnabled: false,
    aiMonthlyLimit: null,
    monthlyLimit: 0,
    description: "Shopify API catalog integration & search",
    featureFlags: {
      "shopify.products": true,
      "shopify.cart": false,
      "shopify.checkout": false,
      "shopify.customer_auth": false,
      openai: false,
      "ai.chatbot": false,
      "ai.recommendations": false,
      "ai.support": false,
    },
    features: [
      "Shopify API catalog integration",
      "Product search and queries",
      "Product details and specifications",
      "No paid subscription required",
    ],
  },
  STARTER: {
    name: "STARTER",
    displayName: "Starter",
    price: 29.0,
    billingType: "RECURRING",
    billingInterval: "MONTHLY",
    aiUsageEnabled: false,
    aiMonthlyLimit: null,
    monthlyLimit: 0,
    description: "Shopify Storefront API, Cart Management & Checkout",
    featureFlags: {
      "shopify.products": true,
      "shopify.cart": true,
      "shopify.checkout": true,
      "shopify.customer_auth": true,
      openai: false,
      "ai.chatbot": false,
      "ai.recommendations": false,
      "ai.support": false,
    },
    features: [
      "Everything in Free",
      "Shopify Storefront API",
      "Add to Cart & variant selection",
      "Cart management & updates",
      "Shopify Checkout creation",
      "Promo & discount code validation",
      "Live shipping rates calculation",
    ],
  },
  PRO: {
    name: "PRO",
    displayName: "Pro",
    price: 79.0,
    billingType: "RECURRING",
    billingInterval: "MONTHLY",
    aiUsageEnabled: true,
    aiMonthlyLimit: null,
    monthlyLimit: 0,
    description: "AI Sales Assistant & BYOK (OpenAI / Gemini)",
    featureFlags: {
      "shopify.products": true,
      "shopify.cart": true,
      "shopify.checkout": true,
      "shopify.customer_auth": true,
      openai: true,
      "ai.chatbot": true,
      "ai.recommendations": true,
      "ai.support": true,
    },
    features: [
      "Everything in Starter",
      "AI sales assistant & AI-powered chatbot",
      "AI personalized product recommendations",
      "AI customer support & knowledge base",
      "OpenAI & Google Gemini integrations",
      "Store owner's own API keys (BYOK)",
      "Priority API throughput & analytics",
    ],
  },
  GROWTH: {
    name: "GROWTH",
    displayName: "Growth",
    price: 79.0,
    billingType: "RECURRING",
    billingInterval: "MONTHLY",
    aiUsageEnabled: true,
    aiMonthlyLimit: null,
    monthlyLimit: 0,
    description: "Full AI Sales Assistant & Knowledge Base",
    featureFlags: {
      "shopify.products": true,
      "shopify.cart": true,
      "shopify.checkout": true,
      "shopify.customer_auth": true,
      openai: true,
      "ai.chatbot": true,
      "ai.recommendations": true,
      "ai.support": true,
    },
    features: [
      "Everything in Starter",
      "AI sales assistant & AI-powered chatbot",
      "AI personalized product recommendations",
      "AI customer support & knowledge base",
      "OpenAI & Google Gemini integrations",
      "Store owner's own API keys (BYOK)",
      "Priority API throughput & analytics",
    ],
  },
};

/**
 * The standard 3 tiers displayed across the platform.
 */
export const ACTIVE_PLAN_TIERS: PlanTier[] = ["FREE", "STARTER", "PRO"];

export interface FeatureMatrixRow {
  feature: string;
  category: "purchase" | "shopify" | "ai" | "quota";
  free: string | boolean;
  starter: string | boolean;
  pro: string | boolean;
}

/**
 * Single source of truth for the comparison matrix table.
 */
export const FEATURE_MATRIX_ROWS: FeatureMatrixRow[] = [
  {
    feature: "Monthly price",
    category: "purchase",
    free: "$0 / mo",
    starter: "$29 / mo",
    pro: "$79 / mo",
  },
  {
    feature: "Shopify API catalog integration",
    category: "shopify",
    free: true,
    starter: true,
    pro: true,
  },
  {
    feature: "Product search & queries",
    category: "shopify",
    free: true,
    starter: true,
    pro: true,
  },
  {
    feature: "Product details & specifications",
    category: "shopify",
    free: true,
    starter: true,
    pro: true,
  },
  {
    feature: "Add to Cart & variant selection",
    category: "shopify",
    free: false,
    starter: true,
    pro: true,
  },
  {
    feature: "Cart management & updates",
    category: "shopify",
    free: false,
    starter: true,
    pro: true,
  },
  {
    feature: "Shopify Checkout creation",
    category: "shopify",
    free: false,
    starter: true,
    pro: true,
  },
  {
    feature: "Promo & discount code validation",
    category: "shopify",
    free: false,
    starter: true,
    pro: true,
  },
  {
    feature: "Live shipping rates calculation",
    category: "shopify",
    free: false,
    starter: true,
    pro: true,
  },
  {
    feature: "Customer Login & Registration",
    category: "shopify",
    free: false,
    starter: true,
    pro: true,
  },
  {
    feature: "AI-powered chatbot assistant",
    category: "ai",
    free: false,
    starter: false,
    pro: true,
  },
  {
    feature: "AI personalized recommendations",
    category: "ai",
    free: false,
    starter: false,
    pro: true,
  },
  {
    feature: "AI customer support",
    category: "ai",
    free: false,
    starter: false,
    pro: true,
  },
  {
    feature: "AI knowledge base",
    category: "ai",
    free: false,
    starter: false,
    pro: true,
  },
  {
    feature: "OpenAI integration",
    category: "ai",
    free: false,
    starter: false,
    pro: true,
  },
  {
    feature: "Google Gemini integration",
    category: "ai",
    free: false,
    starter: false,
    pro: true,
  },
  {
    feature: "Store-owner API key (BYOK)",
    category: "ai",
    free: false,
    starter: false,
    pro: true,
  },
  {
    feature: "App AI message quota",
    category: "quota",
    free: "N/A",
    starter: "N/A",
    pro: "Unlimited (BYOK)",
  },
  {
    feature: "Priority API throughput & analytics",
    category: "quota",
    free: false,
    starter: false,
    pro: true,
  },
];

export function getPlanFeatureMatrix(): FeatureMatrixRow[] {
  return FEATURE_MATRIX_ROWS;
}

/**
 * Check whether a specific plan tier has permission to use a feature.
 */
export function canUseFeature(
  plan: PlanTier | string | null | undefined,
  feature: FeatureKey,
  customFeatureFlags?: Record<string, boolean> | null
): boolean {
  if (!plan) return false;
  
  if (customFeatureFlags && typeof customFeatureFlags === "object") {
    if (customFeatureFlags[feature] === true) return true;
    if (feature.startsWith("ai.") && customFeatureFlags.openai === true) return true;
  }

  const normalizedPlan = plan.toString().toUpperCase() as PlanTier;
  const config = PLAN_CONFIGS[normalizedPlan];
  if (!config) {
    // Dynamic or unknown plan fallback: if feature is basic shopify, default to true; if AI, check if plan has 'PRO' or 'AI' in name
    if (feature.startsWith("shopify.")) return true;
    if (normalizedPlan.includes("PRO") || normalizedPlan.includes("AI") || normalizedPlan.includes("ENTERPRISE")) return true;
    return false;
  }

  // Base feature lookup
  if (config.featureFlags[feature] === true) {
    return true;
  }

  // Parent alias resolution: if checking "ai.chatbot" or "ai.support", "openai" feature satisfies it
  if (feature.startsWith("ai.") && config.featureFlags.openai) {
    return true;
  }

  return false;
}

/**
 * Asserts that a plan has access to a feature, throwing an error if denied.
 */
export class FeatureAccessError extends Error {
  statusCode = 403;
  code = "FEATURE_NOT_AVAILABLE";
  plan: string;
  feature: FeatureKey;

  constructor(plan: string, feature: FeatureKey, customMessage?: string) {
    const message =
      customMessage ||
      `Feature '${feature}' is not included in the ${plan} plan. Please upgrade your plan to access this feature.`;
    super(message);
    this.name = "FeatureAccessError";
    this.plan = plan;
    this.feature = feature;
  }
}

export function assertCanUseFeature(plan: PlanTier | string | null | undefined, feature: FeatureKey, customMessage?: string): void {
  if (!canUseFeature(plan, feature)) {
    throw new FeatureAccessError(String(plan || "UNKNOWN"), feature, customMessage);
  }
}
