-- Phase 18 therapist profile repair
-- Creates a missing therapist profile for an ACTIVE user who has the THERAPIST role.
-- Existing therapist profiles (including intentionally inactive ones) are not changed.

INSERT INTO therapists (user_id, professional_title, registration_number, status, notes)
SELECT DISTINCT u.id, NULL, NULL, 'active', 'Auto-created for existing THERAPIST user during profile repair.'
FROM users u
INNER JOIN user_roles ur ON ur.user_id = u.id
INNER JOIN roles r ON r.id = ur.role_id AND r.name = 'THERAPIST'
LEFT JOIN therapists t ON t.user_id = u.id
WHERE u.status = 'active' AND t.id IS NULL;
