DROP FUNCTION IF EXISTS send_message(uuid,text,text);

CREATE
OR REPLACE FUNCTION public.send_message(
    thread_uuid UUID,
    sender_content TEXT,
    recipient_content TEXT
) RETURNS UUID AS $$
DECLARE
message_id UUID;
    recipient_uuid
UUID;
BEGIN
    IF
NOT EXISTS (
        SELECT 1
        FROM thread_participants tp
        WHERE tp.thread_id = thread_uuid
        AND tp.user_uuid = auth.uid()
    ) THEN
        RAISE EXCEPTION 'User not authorized to send message in this thread';
END IF;

    -- Get the recipient's UUID (the other participant)
SELECT tp.user_uuid
INTO recipient_uuid
FROM thread_participants tp
WHERE tp.thread_id = thread_uuid
  AND tp.user_uuid != auth.uid()
    LIMIT 1;

-- Insert message with both encrypted versions
INSERT INTO messages (thread_id,
                      sender_uuid,
                      sender_content,
                      recipient_content)
VALUES (thread_uuid,
        auth.uid(),
        sender_content,
        recipient_content) RETURNING id
INTO message_id;

RETURN message_id;
END;
$$
LANGUAGE plpgsql SECURITY DEFINER;