import { db } from '@/db/client';
import { buildShopifyAuthUrl } from '@/lib/shopify/oauth';
import { APP_URLS } from '@/config/app';
import ShopifyOAuthEscape from '@/components/auth/ShopifyOAuthEscape';
import PixelManagementPage from './pixel/page';

export const dynamic = 'force-dynamic';

interface HomePageProps {
  searchParams?: Promise<{ shop?: string; host?: string; embedded?: string }> | { shop?: string; host?: string; embedded?: string };
}

export default async function HomePage(props: HomePageProps) {
  const searchParams = props.searchParams ? await Promise.resolve(props.searchParams) : undefined;
  const rawShop = searchParams?.shop;

  if (rawShop) {
    const cleanShop = rawShop.trim().toLowerCase().replace(/^https?:\/\//, '').replace(/\/.*$/, '');
    const normalizedShop = cleanShop.includes('.') ? cleanShop : `${cleanShop}.myshopify.com`;

    try {
      const existingShop = await db.getShopByDomain(normalizedShop);

      if (
        !existingShop ||
        existingShop.status !== 'installed' ||
        !existingShop.access_token_encrypted
      ) {
        const { url: authorizeUrl } = buildShopifyAuthUrl(
          normalizedShop,
          APP_URLS.authCallback()
        );
        return <ShopifyOAuthEscape authorizeUrl={authorizeUrl} shop={normalizedShop} />;
      }
    } catch (err: unknown) {
      console.warn('[HomePage] Shop existence check error:', err);
    }
  }

  return <PixelManagementPage initialMode="onboarding" />;
}
