export type AppSession = {
  accessToken: string;
  refreshToken: string;
  tokenType: string;
  user: {
    id: string;
    role: string;
    email?: string | null;
    phone?: string | null;
    status?: string | null;
  };
  profile?: {
    customerId?: string | null;
    driverId?: string | null;
    restaurantId?: string | null;
    walletId?: string | null;
  };
};

export const RESTAURANT_SESSION_KEY = 'chego-restaurant-session';

export function readSession(): AppSession | null {
  if (typeof window === 'undefined') {
    return null;
  }

  const raw = window.localStorage.getItem(RESTAURANT_SESSION_KEY);
  if (!raw) {
    return null;
  }

  try {
    return JSON.parse(raw) as AppSession;
  } catch {
    window.localStorage.removeItem(RESTAURANT_SESSION_KEY);
    return null;
  }
}

export function writeSession(session: AppSession) {
  window.localStorage.setItem(RESTAURANT_SESSION_KEY, JSON.stringify(session));
}

export function clearSession() {
  window.localStorage.removeItem(RESTAURANT_SESSION_KEY);
}

export function hasRestaurantAccess(session: AppSession | null) {
  return session?.user.role === 'RESTAURANT';
}
