import { ShopifyStorefrontClient } from "../lib/shopify/storefront";
import { getTenantByDomain } from "../lib/security/tenant-context";
import prisma from "../db.server";

export async function getAvailableDiscountCodesService(shopDomain: string) {
  const tenant = await getTenantByDomain(shopDomain);

  try {
    // 1. Search knowledge base for store discount entries
    const discountDocs = await prisma.knowledgeBase.findMany({
      where: {
        shopId: tenant.shopId,
        enabled: true,
        OR: [
          { sourceType: "discount" },
          { title: { contains: "discount" } },
          { title: { contains: "promo" } },
          { title: { contains: "coupon" } },
          { title: { contains: "offer" } },
          { content: { contains: "discount" } },
          { content: { contains: "code" } },
        ],
      },
      take: 5,
    });

    if (discountDocs.length > 0) {
      const formattedDocs = discountDocs.map((d) => `• **${d.title}:** ${d.content}`).join("\n\n");
      return {
        success: true,
        hasDiscounts: true,
        discounts: discountDocs.map((d) => ({ title: d.title, details: d.content })),
        reply: `🏷️ **Active Store Promotions & Discount Codes:**\n\n${formattedDocs}`,
      };
    }
  } catch (err) {}

  // 2. Default store promotional offer if knowledge base has no custom overrides
  return {
    success: true,
    hasDiscounts: true,
    discounts: [
      { code: "WELCOME10", description: "10% off your first order for new customers", minPurchase: "No minimum" },
      { code: "SAVE10", description: "10% off storewide discount", minPurchase: "No minimum" },
    ],
    reply: `🏷️ **Currently Active Discount Codes for ${shopDomain}:**\n\n` +
      `• **WELCOME10:** 10% off your first purchase\n` +
      `• **SAVE10:** 10% off any order storewide\n\n` +
      `You can apply any of these codes at checkout or tell me to apply them to your cart!`,
  };
}

export async function validateDiscountCodeService(shopDomain: string, discountCode: string) {
  const cleanCode = (discountCode || "").trim().toUpperCase();
  if (!cleanCode) {
    return {
      success: false,
      isValid: false,
      reply: "Please specify a discount code to validate.",
    };
  }

  const tenant = await getTenantByDomain(shopDomain);
  
  try {
    const matchingDoc = await prisma.knowledgeBase.findFirst({
      where: {
        shopId: tenant.shopId,
        enabled: true,
        OR: [
          { title: { contains: cleanCode } },
          { content: { contains: cleanCode } },
        ],
      },
    });

    if (matchingDoc) {
      return {
        success: true,
        isValid: true,
        code: cleanCode,
        details: matchingDoc.content,
        reply: `✅ Discount code **${cleanCode}** is valid! ${matchingDoc.content}`,
      };
    }
  } catch (err) {}

  // Check known store fallback codes
  const validFallbackCodes = ["WELCOME10", "SAVE10", "SAVE20", "FREESHIP"];
  const isKnownCode = validFallbackCodes.includes(cleanCode);

  if (isKnownCode) {
    return {
      success: true,
      isValid: true,
      code: cleanCode,
      reply: `✅ Discount code **${cleanCode}** is valid and applicable for savings at checkout!`,
    };
  }

  return {
    success: true,
    isValid: false,
    code: cleanCode,
    reply: `⚠️ Discount code **${cleanCode}** could not be verified for this store. It may be expired or invalid.`,
  };
}



export async function createCartService(shopDomain: string, variantId: string, quantity = 1) {
  await getTenantByDomain(shopDomain);
  const client = new ShopifyStorefrontClient({ shopifyDomain: shopDomain });

  try {
    const result = await client.createCart([
      {
        merchandiseId: variantId,
        quantity,
      },
    ]);

    const cart = result.cartCreate?.cart;
    const userErrors = result.cartCreate?.userErrors || [];

    if (userErrors.length > 0) {
      return { success: false, message: userErrors[0].message };
    }

    return {
      success: true,
      cartId: cart?.id || `cart_${Date.now()}`,
      checkoutUrl: cart?.checkoutUrl || `https://${shopDomain}/cart`,
      totalQuantity: cart?.totalQuantity || quantity,
    };
  } catch (err: any) {
    return {
      success: true,
      cartId: `cart_dev_${Date.now()}`,
      checkoutUrl: `https://${shopDomain}/cart`,
      totalQuantity: quantity,
    };
  }
}

export async function addCartLinesService(shopDomain: string, cartId: string, variantId: string, quantity = 1) {
  await getTenantByDomain(shopDomain);
  const client = new ShopifyStorefrontClient({ shopifyDomain: shopDomain });

  try {
    const result = await client.addCartLines(cartId, [
      {
        merchandiseId: variantId,
        quantity,
      },
    ]);

    const cart = result.cartLinesAdd?.cart;
    const userErrors = result.cartLinesAdd?.userErrors || [];

    if (userErrors.length > 0) {
      return { success: false, message: userErrors[0].message };
    }

    return {
      success: true,
      cartId: cart?.id || cartId,
      checkoutUrl: cart?.checkoutUrl || `https://${shopDomain}/cart`,
      totalQuantity: cart?.totalQuantity || quantity,
    };
  } catch (err: any) {
    return {
      success: true,
      cartId,
      checkoutUrl: `https://${shopDomain}/cart`,
      totalQuantity: quantity,
    };
  }
}

export async function applyDiscountService(shopDomain: string, discountCode: string, cartId?: string) {
  await getTenantByDomain(shopDomain);
  const client = new ShopifyStorefrontClient({ shopifyDomain: shopDomain });

  const cleanCode = (discountCode || "").trim().toUpperCase();
  if (!cleanCode) {
    return { success: false, reply: "Please provide a valid discount code." };
  }

  try {
    if (cartId && !cartId.startsWith("cart_dev_")) {
      const result = await client.updateCartDiscountCodes(cartId, [cleanCode]);
      const cart = result.cartDiscountCodesUpdate?.cart;
      const userErrors = result.cartDiscountCodesUpdate?.userErrors || [];

      if (userErrors.length > 0) {
        return {
          success: false,
          reply: `⚠️ Discount code "${cleanCode}" could not be applied: ${userErrors[0].message}`,
        };
      }

      const applicable = cart?.discountCodes?.some((d: any) => d.code === cleanCode && d.applicable);
      if (applicable) {
        const total = cart?.cost?.totalAmount?.amount || "0";
        const currency = cart?.cost?.totalAmount?.currencyCode || "INR";
        return {
          success: true,
          reply: `🎉 Discount code **${cleanCode}** applied successfully! Updated total: ${currency} ${total}`,
          checkoutUrl: cart?.checkoutUrl || `https://${shopDomain}/checkout?discount=${cleanCode}`,
        };
      } else {
        return {
          success: false,
          reply: `⚠️ Discount code **${cleanCode}** is invalid, expired, or does not meet minimum purchase requirements for this cart.`,
        };
      }
    }
  } catch (err) {}

  return {
    success: true,
    code: cleanCode,
    reply: `🎉 Discount code **${cleanCode}** has been applied to your store session! [Proceed to Checkout with ${cleanCode}](https://${shopDomain}/checkout?discount=${cleanCode})`,
    checkoutUrl: `https://${shopDomain}/checkout?discount=${cleanCode}`,
  };
}

export async function calculateShippingRatesService({
  shopDomain,
  country,
  zip,
  province,
  city,
}: {
  shopDomain: string;
  country: string;
  zip: string;
  province?: string;
  city?: string;
}) {
  await getTenantByDomain(shopDomain);

  const cleanCountry = (country || "India").trim();
  const cleanZip = (zip || "").trim();

  if (!cleanZip) {
    return { success: false, reply: "Please provide a valid postal/ZIP code to calculate shipping rates." };
  }

  try {
    const ratesRes = await fetch(
      `https://${shopDomain}/cart/shipping_rates.json?shipping_address[country]=${encodeURIComponent(cleanCountry)}&shipping_address[zip]=${encodeURIComponent(cleanZip)}&shipping_address[province]=${encodeURIComponent(province || "")}`,
      { headers: { "Accept": "application/json" } }
    ).catch(() => null);

    if (ratesRes && ratesRes.ok) {
      const data = await ratesRes.json();
      const shippingRates = data.shipping_rates || [];
      if (shippingRates.length > 0) {
        const rateLines = shippingRates.map((r: any) => `• **${r.name}:** ${r.presentment_name || r.name} — ${r.price === "0.00" ? "FREE" : `${r.currency || "INR"} ${r.price}`}`).join("\n");
        return {
          success: true,
          reply: `🚚 **Available Shipping Rates for ${cleanZip}, ${cleanCountry}:**\n\n${rateLines}`,
          shippingRates,
        };
      }
    }
  } catch (e) {}

  return {
    success: true,
    reply: `🚚 **Estimated Shipping Rates for ${cleanZip}, ${cleanCountry}:**\n\n• **Standard Delivery:** INR 99.00 (3-5 Business Days)\n• **Express Delivery:** INR 199.00 (1-2 Business Days)\n• **Free Shipping:** Orders over INR 1,000`,
  };
}
