-- Add change password function for users
-- This migration adds a function to allow users to change their own password

-- Function to change user password (user can only change their own password)
CREATE OR REPLACE FUNCTION public.change_user_password(
    current_password TEXT,
    new_password TEXT
)
RETURNS JSON AS $$
DECLARE
    user_id UUID;
    user_email TEXT;
    result JSON;
BEGIN
    -- Get current user ID
    user_id := auth.uid();
    
    IF user_id IS NULL THEN
        RAISE EXCEPTION 'User not authenticated';
    END IF;
    
    -- Get user email
    SELECT email INTO user_email
    FROM public.user_profiles 
    WHERE id = user_id;
    
    IF user_email IS NULL THEN
        RAISE EXCEPTION 'User profile not found';
    END IF;
    
    -- Verify current password
    IF NOT EXISTS (
        SELECT 1 
        FROM auth.users 
        WHERE id = user_id 
        AND encrypted_password = crypt(current_password, encrypted_password)
    ) THEN
        RAISE EXCEPTION 'Current password is incorrect';
    END IF;
    
    -- Update the password in auth.users table
    UPDATE auth.users 
    SET 
        encrypted_password = crypt(new_password, gen_salt('bf')),
        updated_at = NOW()
    WHERE id = user_id;
    
    -- Return result
    result := json_build_object(
        'user_id', user_id,
        'email', user_email,
        'password_changed_at', NOW()
    );
    
    RETURN result;
    
EXCEPTION
    WHEN OTHERS THEN
        RAISE;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;

