-- Add password reset function for admin use
-- This migration adds a function to reset user passwords back to the default "password123"

-- Function to reset user password (admin only)
CREATE OR REPLACE FUNCTION public.reset_user_password(
    target_user_id UUID
)
RETURNS JSON AS $$
DECLARE
    user_email TEXT;
    result JSON;
BEGIN
    -- Only admins can reset passwords
    IF NOT public.is_admin() THEN
        RAISE EXCEPTION 'Only administrators can reset user passwords';
    END IF;
    
    -- Check if target user exists
    SELECT email INTO user_email
    FROM public.user_profiles 
    WHERE id = target_user_id;
    
    IF user_email IS NULL THEN
        RAISE EXCEPTION 'User not found';
    END IF;
    
    -- Update the password in auth.users table
    UPDATE auth.users 
    SET 
        encrypted_password = crypt('password123', gen_salt('bf')),
        updated_at = NOW()
    WHERE id = target_user_id;
    
    -- Return result
    result := json_build_object(
        'user_id', target_user_id,
        'email', user_email,
        'new_password', 'password123',
        'reset_at', NOW()
    );
    
    RETURN result;
    
EXCEPTION
    WHEN OTHERS THEN
        RAISE;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;

