-- ============================================================
-- Setup: Initial Admin User and Authentication
-- ============================================================
-- Run this SQL after creating your first user in Supabase Auth

-- Step 1: Create helper function to check admin status
CREATE OR REPLACE FUNCTION is_admin(user_id UUID)
RETURNS BOOLEAN AS $$
BEGIN
  RETURN EXISTS (
    SELECT 1 FROM public.admin_users 
    WHERE id = user_id
  );
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;

-- Step 2: Add initial admin user
-- Method A: If user already exists in auth.users, run this:
/*
INSERT INTO public.admin_users (id, email, role)
SELECT id, email, 'admin'
FROM auth.users
WHERE email = 'admin@tabatafit.com'
ON CONFLICT (id) DO NOTHING;
*/

-- Method B: Insert directly with known UUID
-- INSERT INTO public.admin_users (id, email, role) 
-- VALUES ('paste-uuid-here', 'admin@tabatafit.com', 'admin');

-- Step 3: Verify admin setup
SELECT 
  au.id,
  au.email,
  au.role,
  au.created_at,
  u.email as auth_email
FROM public.admin_users au
JOIN auth.users u ON au.id = u.id;

-- Step 4: List all users in auth (to find your UUID)
SELECT id, email, created_at, last_sign_in_at
FROM auth.users
ORDER BY created_at DESC;