import { redirect } from "@remix-run/node";
import type { LoaderFunctionArgs } from "@remix-run/node";
import { getSession, commitSession, destroySession } from "~/lib/session.server";
import { accountLinkingService } from "~/lib/account-linking.server";

export async function loader({ request }: LoaderFunctionArgs) {
  const url = new URL(request.url);
  const service = url.searchParams.get("service");
  const unlink = url.searchParams.get("unlink") === "true";
  
  const session = await getSession(request.headers.get("Cookie"));
  const userSession = session.get("user");
  
  // If no user session, just redirect to home
  if (!userSession) {
    return redirect("/");
  }

  // Handle account unlinking
  if (unlink && userSession.isLinked && userSession.github) {
    console.log(`🔄 Unlinking accounts for GitHub user: ${userSession.github.login}`);
    try {
      // Remove the link from storage
      accountLinkingService.removeLink(userSession.github.userId);
      
      // Update session to reflect unlinked status
      userSession.isLinked = false;
      delete userSession.linkedAt;
      
      // Save updated session
      session.set("user", userSession);
      
      return redirect("/?message=accounts_unlinked", {
        headers: {
          "Set-Cookie": await commitSession(session),
        },
      });
    } catch (error) {
      console.error("Error unlinking accounts:", error);
      return redirect("/?error=unlink_failed");
    }
  }

  // Handle selective logout by service
  if (service) {
    console.log(`🔄 Logging out of ${service} service`);
    
    if (service === "github" && userSession.github) {
      // Remove GitHub info but keep HuggingFace if present
      delete userSession.github;
      
      // If linked, update linking status
      if (userSession.isLinked) {
        userSession.isLinked = false;
        delete userSession.linkedAt;
      }
      
      // Save updated session
      session.set("user", userSession);
      
      return redirect("/", {
        headers: {
          "Set-Cookie": await commitSession(session),
        },
      });
    }
    
    if (service === "huggingface" && userSession.huggingface) {
      // Remove HuggingFace info but keep GitHub if present
      delete userSession.huggingface;
      
      // If linked, update linking status
      if (userSession.isLinked) {
        userSession.isLinked = false;
        delete userSession.linkedAt;
      }
      
      // Save updated session
      session.set("user", userSession);
      
      return redirect("/", {
        headers: {
          "Set-Cookie": await commitSession(session),
        },
      });
    }
  }

  // Full logout (destroy entire session)
  return redirect("/", {
    headers: {
      "Set-Cookie": await destroySession(session),
    },
  });
}