import { useEffect, useState } from "react";
import { router } from "expo-router";
import { ActivityIndicator, View } from "react-native";
import { api, ApiError } from "@/lib/api";
import { clearActiveRestaurant, getActiveRestaurant, setActiveRestaurant } from "@/lib/active-restaurant";
import { configurePurchases } from "@/lib/purchases";
import { supabase } from "@/lib/supabase";

interface MeRestaurantResponse {
  restaurant: {
    id: string;
    slug: string;
    locations: { id: string; menus: { id: string }[] }[];
  } | null;
}

export default function Index() {
  const [checking, setChecking] = useState(true);

  useEffect(() => {
    let cancelled = false;

    async function resolve() {
      try {
        const { data } = await supabase.auth.getSession();
        if (!data?.session) {
          if (!cancelled) {
            router.replace("/(auth)/login");
          }
          return;
        }

        const cached = await getActiveRestaurant();
        if (cached) {
          configurePurchases(cached.restaurantId);
          if (!cancelled) {
            router.replace("/menu");
          }
          return;
        }

        const { restaurant } = await api.get<MeRestaurantResponse>("/me/restaurant");
        const location = restaurant?.locations[0];
        const menu = location?.menus[0];

        if (restaurant && location && menu) {
          await setActiveRestaurant({
            restaurantId: restaurant.id,
            locationId: location.id,
            menuId: menu.id,
            slug: restaurant.slug,
          });
          configurePurchases(restaurant.id);
          if (!cancelled) {
            router.replace("/menu");
          }
          return;
        }
      } catch (e) {
        console.warn("Index resolve error:", e);

        // A 401 here means the cached session's token is no longer valid
        // server-side (expired refresh token, deleted user, etc.) — that is
        // not the same as "no restaurant yet", so send them to login instead
        // of silently starting onboarding with a broken session.
        if (e instanceof ApiError && e.status === 401) {
          await clearActiveRestaurant();
          await supabase.auth.signOut();
          if (!cancelled) {
            router.replace("/(auth)/login");
          }
          return;
        }
      }

      if (!cancelled) {
        router.replace("/(onboarding)/restaurant");
      }
    }

    resolve().finally(() => {
      if (!cancelled) setChecking(false);
    });

    return () => {
      cancelled = true;
    };
  }, []);

  return (
    <View style={{ flex: 1, alignItems: "center", justifyContent: "center", backgroundColor: "#FAF8F5" }}>
      {checking ? <ActivityIndicator size="large" color="#C8A96B" /> : null}
    </View>
  );
}
