import type { ActionFunctionArgs } from "react-router";
import { syncStoreCatalog } from "../services/catalog.server";
import { checkRateLimit } from "../lib/security/rate-limit";
import prisma from "../db.server";

const corsHeaders = {
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Methods": "POST, OPTIONS",
  "Access-Control-Allow-Headers": "*, Content-Type, Authorization, X-Requested-With, Cache-Control, Pragma, Accept, Origin",
  "Access-Control-Max-Age": "86400",
  "Content-Type": "application/json",
};

export const action = async ({ request }: ActionFunctionArgs) => {
  if (request.method === "OPTIONS") {
    return new Response(null, { status: 204, headers: corsHeaders });
  }

  try {
    const body = await request.json().catch(() => ({}));
    const rawShop = body.shop;

    if (!rawShop || typeof rawShop !== "string" || !rawShop.includes(".")) {
      return new Response(
        JSON.stringify({ success: false, message: "Valid shop parameter is required" }),
        { status: 400, headers: corsHeaders }
      );
    }

    const normalizedShop = rawShop.toLowerCase().trim();

    // Verify shop exists in registered DB before syncing
    const existingShop = await prisma.shop.findUnique({
      where: { shopifyDomain: normalizedShop },
    });

    if (!existingShop) {
      return new Response(
        JSON.stringify({ success: false, message: "Unauthorized: Store not registered" }),
        { status: 403, headers: corsHeaders }
      );
    }

    // Rate limit sync requests (max 5 syncs per 10 minutes per shop)
    checkRateLimit({ key: `sync_${normalizedShop}`, maxTokens: 5, refillIntervalMs: 600000 });

    const syncResult = await syncStoreCatalog(normalizedShop);

    return new Response(JSON.stringify(syncResult), {
      headers: corsHeaders,
    });
  } catch (error: any) {
    console.error("[Catalog Sync API Error]:", error);
    const status = error?.statusCode || (error?.message?.includes("Rate limit") ? 429 : 500);
    return new Response(
      JSON.stringify({
        success: false,
        message: error.message || "Failed to sync catalog.",
      }),
      { status, headers: corsHeaders }
    );
  }
};
