import { redirect } from 'next/navigation';
import { getSession } from '@/lib/auth';
import { getEmployeeLandingPath } from '@/lib/employee-permissions';
import { isSetupRequired } from '@/lib/setup/detection';
import { checkCurrentLicense } from '@/lib/license/validator';

export default async function HomePage() {
  // 1. Check if first-run setup is needed
  const setupNeeded = await isSetupRequired().catch(() => false);
  if (setupNeeded) {
    redirect('/setup');
  }

  // 2. Check license validity (skip in dev when SKIP_LICENSE_CHECK=true)
  if (process.env.NODE_ENV !== 'development' || process.env.SKIP_LICENSE_CHECK !== 'true') {
    const license = await checkCurrentLicense().catch(() => ({ valid: false }));
    if (!license.valid) {
      redirect('/license-invalid');
    }
  }

  // 3. Normal auth flow
  const session = await getSession();
  if (session?.user) {
    const settings = await (await import('@/lib/postgres/data-access')).pgGetSettings();
    redirect(getEmployeeLandingPath(session.user, settings));
  } else {
    redirect('/login');
  }
}
