import { redirect } from 'next/navigation';
import { cookies } from 'next/headers';
import { RowDataPacket } from 'mysql2';
import pool from '@/lib/db';
import { CUSTOMER_SESSION_COOKIE, validateCustomerSession } from '@/lib/auth/customerSession';
import { AccountUserProvider } from '@/components/frontend/account/AccountUserContext';

interface UserRow extends RowDataPacket {
  id: string;
  name: string;
  email: string;
  phone: string | null;
  email_verified: number;
}

// Real, server-side route protection for the whole /account section — every
// page under it (dashboard, orders, wishlist, addresses, profile, etc.) is
// covered by this one layout, so none of them can be reached without a
// valid `desicart-customer-session` cookie. This replaces the old
// client-side-only check AccountLayout.tsx used to do (a `fetch` + redirect
// *after* the page had already mounted, which briefly rendered a loading
// spinner in an unauthenticated browser before bouncing them) — this
// redirect happens before any HTML for the page is ever sent.
export default async function AccountRouteLayout({ children }: { children: React.ReactNode }) {
  const cookieStore = await cookies();
  const sessionId = cookieStore.get(CUSTOMER_SESSION_COOKIE)?.value;
  const session = sessionId ? await validateCustomerSession(sessionId) : null;

  if (!session) {
    redirect('/login');
  }

  const [rows] = await pool.query<UserRow[]>(
    `SELECT id, name, email, phone, email_verified FROM users WHERE id = ? AND is_active = 1 LIMIT 1`,
    [session.user_id],
  );
  const user = rows[0];

  // A revoked/deactivated account with a still-technically-valid session
  // row — same "account not found" treatment /api/frontend/auth/me already
  // gives this case.
  if (!user) {
    redirect('/login');
  }

  return (
    <AccountUserProvider
      user={{
        id: user.id,
        name: user.name,
        email: user.email,
        phone: user.phone,
        emailVerified: Boolean(user.email_verified),
      }}
    >
      {children}
    </AccountUserProvider>
  );
}
