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

/**
 * OAuth Callback Route
 * This handles the OAuth redirect from Shopify after merchant authorization
 * Route: /auth/callback
 */
export async function loader({ request }: LoaderFunctionArgs) {
  console.log("=== OAuth Callback Started ===");
  
  try {
    const url = new URL(request.url);
    console.log("Full callback URL:", url.toString());
    
    // Extract OAuth parameters
    const shop = url.searchParams.get("shop");
    const code = url.searchParams.get("code");
    const state = url.searchParams.get("state");
    const hmac = url.searchParams.get("hmac");
    const timestamp = url.searchParams.get("timestamp");
    const host = url.searchParams.get("host");
    
    console.log("OAuth Parameters:", {
      shop,
      code: code ? `${code.substring(0, 10)}...` : null,
      state: state ? `${state.substring(0, 10)}...` : null,
      hmac: hmac ? `${hmac.substring(0, 10)}...` : null,
      timestamp,
      host: host ? `${host.substring(0, 20)}...` : null
    });

    // Step 1: Validate required parameters
    console.log("Step 1: Validating required parameters...");
    if (!shop || !code || !hmac) {
      console.error("❌ Missing required OAuth parameters:", { 
        shop: !!shop, 
        code: !!code, 
        hmac: !!hmac 
      });
      return new Response(
        JSON.stringify({ 
          success: false, 
          error: "Missing required OAuth parameters" 
        }),
        { 
          status: 400,
          headers: { "Content-Type": "application/json" }
        }
      );
    }
    console.log("✓ Required parameters present");

    // Step 2: Validate shop format
    console.log("Step 2: Validating shop format...");
    const shopRegex = /^[a-zA-Z0-9][a-zA-Z0-9\-]*\.myshopify\.com$/;
    if (!shopRegex.test(shop)) {
      console.error("❌ Invalid shop parameter format:", shop);
      return new Response(
        JSON.stringify({ 
          success: false, 
          error: "Invalid shop parameter" 
        }),
        { 
          status: 400,
          headers: { "Content-Type": "application/json" }
        }
      );
    }
    console.log("✓ Shop format valid:", shop);

    // Step 3: Exchange authorization code for access token
    console.log("Step 3: Exchanging authorization code for access token...");
    const { admin, session } = await authenticate.admin(request);
    
    console.log("✓ Authentication successful");
    console.log("Session details:", {
      shop: session.shop,
      id: session.id,
      isOnline: session.isOnline,
      scope: session.scope,
      expires: session.expires ? new Date(session.expires).toISOString() : null,
      accessToken: session.accessToken ? `${session.accessToken.substring(0, 10)}...` : null
    });

    // Step 4: Verify session is stored in database
    console.log("Step 4: Verifying session storage in database...");
    try {
      const storedSession = await prisma.session.findFirst({
        where: { shop: session.shop },
        orderBy: { id: 'desc' }
      });
      
      if (storedSession) {
        console.log("✓ Session found in database:", {
          id: storedSession.id,
          shop: storedSession.shop,
          isOnline: storedSession.isOnline,
        //@ts-expect-error   
          createdAt: storedSession.createdAt
        });
      } else {
        console.warn("⚠️ Session not yet in database (may be stored asynchronously)");
      }
    } catch (dbError) {
      console.error("❌ Database check failed:", dbError);
      // Don't fail the OAuth flow if DB check fails
    }

    // Step 5: Optional - Call your backend to register/login the shop
    // console.log("Step 5: Registering shop with backend API...");
    // try {
    //   const backendResponse = await fetch(
    //     `https://dev.qixs.ai:3003/vendor/shopify/login`,
    //     {
    //       method: "POST",
    //       headers: {
    //         "Content-Type": "application/json",
    //       },
    //       body: JSON.stringify({
    //         storeDomain: session.shop,
    //         accessToken: session.accessToken,
    //       }),
    //     }
    //   );

    //   if (backendResponse.ok) {
    //     const backendData = await backendResponse.json();
    //     console.log("✓ Backend registration successful:", {
    //       hasAgentId: !!backendData?.data?.agent_id,
    //       agentId: backendData?.data?.agent_id
    //     });
    //   } else {
    //     console.warn("⚠️ Backend registration failed:", backendResponse.status);
    //     // Don't block OAuth flow if backend call fails
    //   }
    // } catch (backendError) {
    //   console.error("❌ Backend API call failed:", backendError);
    //   // Don't block OAuth flow if backend fails
    // }
    
    // Step 6: Redirect to app UI
    console.log("Step 6: Preparing redirect to app UI...");
    const isEmbedded = url.searchParams.get("embedded") === "1";
    console.log("Is embedded app:", isEmbedded);
    
    const redirectUrl = `/?shop=${shop}${host ? `&host=${encodeURIComponent(host)}` : ''}`;
    console.log("Redirecting to:", redirectUrl);
    
    console.log("=== OAuth Callback Completed Successfully ===\n");
    return redirect(redirectUrl);

  } catch (error) {
    console.error("=== ❌ FATAL: OAuth Callback Failed ===");
    console.error("Error type:", error instanceof Error ? error.constructor.name : typeof error);
    console.error("Error message:", error instanceof Error ? error.message : String(error));
    console.error("Full error:", error);
    
    // Log request details for debugging
    console.error("Request URL:", request.url);
    console.error("Request method:", request.method);
    
    return new Response(
      JSON.stringify({
        success: false,
        error: error instanceof Error ? error.message : "Internal server error",
      }),
      { 
        status: 500,
        headers: { "Content-Type": "application/json" }
      }
    );
  }
}
