import { redirect } from 'next/navigation';
import { createSupabaseServerClient } from '@/lib/supabase/server';
import { getSupabaseAdmin } from '@/lib/supabase/admin';
import { ActivateClient } from './activate-client';

export const dynamic = 'force-dynamic';

export default async function ActivatePage({
  searchParams,
}: {
  searchParams: { code?: string };
}) {
  const supabase = createSupabaseServerClient();
  const {
    data: { user },
  } = await supabase.auth.getUser();
  if (!user) redirect('/login?next=/activate');

  const admin = getSupabaseAdmin();
  const { data: tunnel } = await admin
    .from('tunnels')
    .select('subdomain')
    .eq('user_id', user.id)
    .maybeSingle<{ subdomain: string }>();

  return (
    <div>
      <h1>Activate device</h1>
      <p className="muted">
        Enter the code shown by your Home Assistant add-on to pair it with your
        account.
      </p>
      <div className="card">
        <ActivateClient
          prefillCode={searchParams.code ?? ''}
          currentSubdomain={tunnel?.subdomain ?? null}
        />
      </div>
    </div>
  );
}
