import type { LoaderFunctionArgs } from "react-router";
import { authenticate } from "../shopify.server";
import prisma from "../db.server";

/**
 * Widget Token App Proxy Endpoint
 * This endpoint is accessed via: https://shop.myshopify.com/apps/qixs
 * It generates a token with agent_id for the chat widget
 */
export async function loader({ request }: LoaderFunctionArgs) {
  try {
    // Authenticate using app proxy
    await authenticate.public.appProxy(request);

    // Get shop domain from query params (added by Shopify)
    const url = new URL(request.url);
    const shopDomain = url.searchParams.get("shop");

    console.log(`[Widget Token] Incoming request: ${request.url}`);
    console.log(`[Widget Token] shopDomain: ${shopDomain}`);

    if (!shopDomain) {
      console.error(`[Widget Token] Missing shop parameter`);
      return new Response(
        JSON.stringify({ success: false, error: "Shop parameter is required" }),
        {
          status: 400,
          headers: { "Content-Type": "application/json" }
        }
      );
    }

    // Get agent ID for this shop
    const agentId = await getAgentIdForShop(shopDomain);
    console.log(`[Widget Token] agentId: ${agentId}`);

    // Generate token using agent ID
    const token = generateToken(agentId);
    console.log(`[Widget Token] token generated: ${token}`);

    // Return token as JSON
    console.log(`[Widget Token] Responding with token for shop: ${shopDomain}`);
    return new Response(
      JSON.stringify({
        success: true,
        token: token,
      }),
      {
        status: 200,
        headers: { "Content-Type": "application/json" }
      }
    );
  } catch (error) {
    console.error("[Widget Token] Error:", error);
    return new Response(
      JSON.stringify({
        success: false,
        error: error instanceof Error ? error.message : "Internal server error",
      }),
      {
        status: 500,
        headers: { "Content-Type": "application/json" }
      }
    );
  }
}

/**
 * Generate token from agent ID
 * Matches your frontend generateToken logic
 */
function generateToken(agentId: string): string {
  const token = Buffer.from(
    JSON.stringify({
      agent_id: agentId,
    })
  )
    .toString("base64")
    .replace(/\+/g, "-")
    .replace(/\//g, "_")
    .replace(/=+$/, "");
  console.log(`[Widget Token] generateToken called for agentId: ${agentId}, token: ${token}`);
  return token;
}

/**
 * Get agent ID for the shop
 * Calls your backend API to get user info with agent ID
 */
async function getAgentIdForShop(shopDomain: string): Promise<string> {
  try {
    // Get session from database to get access token
    const session = await prisma.session.findFirst({
      where: { shop: shopDomain },
      orderBy: { id: 'desc' }
    });

    console.log("[Widget Token] [SESSION IN api.widget-token]", session);

    if (!session) {
      throw new Error(`No session found for shop: ${shopDomain}`);
    }

    // Call your backend API to get agent ID
    const response = await fetch(
      // `https://dev.qixs.ai:3003/vendor/shopify/login`,
      `https://dev.qixs.ai:3003/vendor/shopify/login`,
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          storeDomain: shopDomain,
          accessToken: session.accessToken,
        }),
      }
    );

    console.log(`[Widget Token] Called backend login API for shop: ${shopDomain}`);
    if (!response.ok) {
      throw new Error(`Backend API error: ${response.status} ${response.statusText}`);
    }
    const data = await response.json();
    console.log("[Widget Token] [call LOGIN API]", data);
    // Try to get agent ID from response
    if (data?.data?.agent_id) {
      console.log(`[Widget Token] agent_id found in backend response: ${data.data.agent_id}`);
      return data.data.agent_id;
    }
    throw new Error("No agent_id found in backend response");
  } catch (error) {
    console.error("[Widget Token] Error getting agent ID:", error);
    throw error;
  }
}
