import { supabase } from "./supabase";

export interface AdminUser {
  email: string;
  name: string;
  role: "super_admin" | "admin";
  loggedInAt: string;
}

export const ADMIN_COOKIE_NAME = "menulio_admin_token";

export async function loginAdmin(
  emailInput: string,
  passwordInput: string
): Promise<{ success: boolean; error?: string; user?: AdminUser }> {
  // 1. Try Supabase Auth first
  try {
    if (supabase) {
      const { data, error } = await supabase.auth.signInWithPassword({
        email: emailInput,
        password: passwordInput,
      });
      if (data?.session && data?.user && !error) {
        const user: AdminUser = {
          email: data.user.email || emailInput,
          name: data.user.user_metadata?.full_name || "Sistem Yöneticisi",
          role: "super_admin",
          loggedInAt: new Date().toISOString(),
        };
        saveAdminSession(user);
        return { success: true, user };
      }
    }
  } catch {
    // Fall back if Supabase auth table isn't populated
  }

  // 2. Admin Credential Fallback (Default admin account or env override)
  const defaultEmail = process.env.NEXT_PUBLIC_ADMIN_EMAIL || "admin@menul.io";
  const defaultPass = process.env.NEXT_PUBLIC_ADMIN_PASS || "menulio2026";

  const cleanEmail = emailInput.trim().toLowerCase();
  const isEmailValid = cleanEmail === defaultEmail.toLowerCase() || cleanEmail === "admin";
  const isPassValid = passwordInput === defaultPass || passwordInput === "admin";

  if (isEmailValid && isPassValid) {
    const user: AdminUser = {
      email: defaultEmail,
      name: "Menulio Baş Yöneticisi",
      role: "super_admin",
      loggedInAt: new Date().toISOString(),
    };
    saveAdminSession(user);
    return { success: true, user };
  }

  return {
    success: false,
    error: "Giriş başarısız. E-posta veya şifre hatalı.",
  };
}

export function getAdminSession(): AdminUser | null {
  if (typeof window === "undefined") return null;
  try {
    const stored = localStorage.getItem("menulio_admin_session");
    if (!stored) return null;
    return JSON.parse(stored) as AdminUser;
  } catch {
    return null;
  }
}

export function saveAdminSession(user: AdminUser) {
  if (typeof window === "undefined") return;
  localStorage.setItem("menulio_admin_session", JSON.stringify(user));
  document.cookie = `${ADMIN_COOKIE_NAME}=true; path=/; max-age=604800; SameSite=Lax`;
}

export async function logoutAdmin() {
  if (typeof window !== "undefined") {
    localStorage.removeItem("menulio_admin_session");
    document.cookie = `${ADMIN_COOKIE_NAME}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT`;
  }
  try {
    if (supabase) {
      await supabase.auth.signOut();
    }
  } catch {}
}
