import { getServerSession } from "next-auth/next";
import { authOptions } from "@/app/api/auth/[...nextauth]/route";
import { redirect } from "next/navigation";
import { ResponsiveIframe } from "@/app/components/responsive-iframe";
import RocketChatAuth from "@/app/components/rocket-auth";

// Function to get Rocket.Chat token for server-side authentication
async function getRocketChatTokensServer(email: string) {
  try {
    const baseUrl = process.env.NEXT_PUBLIC_IFRAME_PAROLE_URL?.split('/channel')[0];
    if (!baseUrl) return null;

    // Admin headers for Rocket.Chat API
    const adminHeaders = {
      'X-Auth-Token': process.env.ROCKET_CHAT_TOKEN!,
      'X-User-Id': process.env.ROCKET_CHAT_USER_ID!,
      'Content-Type': 'application/json'
    };

    // Get the username from email
    const username = email.split('@')[0];
    
    // Get all users to find the current user
    const usersResponse = await fetch(`${baseUrl}/api/v1/users.list`, {
      method: 'GET',
      headers: adminHeaders,
      cache: 'no-store' // Don't cache this request
    });

    if (!usersResponse.ok) return null;

    const usersData = await usersResponse.json();
    
    // Find the current user in the list
    const currentUser = usersData.users.find((user: any) => 
      user.username === username || 
      (user.emails && user.emails.some((emailObj: any) => emailObj.address === email))
    );

    if (!currentUser) return null;

    // Create a token for the current user
    const createTokenResponse = await fetch(`${baseUrl}/api/v1/users.createToken`, {
      method: 'POST',
      headers: adminHeaders,
      body: JSON.stringify({
        userId: currentUser._id
      }),
      cache: 'no-store' // Don't cache this request
    });

    if (!createTokenResponse.ok) return null;

    const tokenData = await createTokenResponse.json();
    
    return {
      token: tokenData.data.authToken,
      userId: currentUser._id
    };
  } catch (error) {
    console.error('Error getting server-side Rocket.Chat token:', error);
    return null;
  }
}

export default async function Page() {
  const session = await getServerSession(authOptions);

  if (!session) {
    redirect("/signin");
  }

  // Try to get Rocket.Chat tokens server-side
  let rocketChatUrl = process.env.NEXT_PUBLIC_IFRAME_PAROLE_URL || '';
  
  if (session.user?.email) {
    const rocketTokens = await getRocketChatTokensServer(session.user.email);
    
    if (rocketTokens) {
      // Add token to URL for direct authentication
      // Note: This is only for development/testing - in production,
      // consider more secure methods
      const urlObj = new URL(rocketChatUrl);
      urlObj.searchParams.set('resumeToken', rocketTokens.token);
      urlObj.searchParams.set('rc_uid', rocketTokens.userId);
      urlObj.searchParams.set('rc_token', rocketTokens.token);
      rocketChatUrl = urlObj.toString();
    }
  }

  return (
    <main className="w-full h-screen bg-black">
      {/* Keep RocketChatAuth for client-side backup authentication */}
      <RocketChatAuth />
      
      <div className="w-full h-full px-4 pt-12 pb-4">
        <ResponsiveIframe 
          src={rocketChatUrl}
          allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
        />
      </div>
    </main>
  );
} 