-- Link users to iTop Person
ALTER TABLE users ADD COLUMN IF NOT EXISTS itop_person_id INTEGER;
ALTER TABLE users ADD COLUMN IF NOT EXISTS last_itop_sync TIMESTAMP;
ALTER TABLE users ADD COLUMN IF NOT EXISTS force_password_change BOOLEAN DEFAULT false;

-- source already implied by auth_type, no change

-- Link contacts to iTop Person
ALTER TABLE contacts ADD COLUMN IF NOT EXISTS itop_id INTEGER;
ALTER TABLE contacts ADD COLUMN IF NOT EXISTS telephone VARCHAR(50);
ALTER TABLE contacts ADD COLUMN IF NOT EXISTS team VARCHAR(100);
ALTER TABLE contacts ADD COLUMN IF NOT EXISTS function VARCHAR(200);

-- Unique constraint on email for linking users
CREATE UNIQUE INDEX IF NOT EXISTS users_email_unique_active ON users (LOWER(email)) WHERE email IS NOT NULL AND email != '';

-- Match existing users to contacts by email
UPDATE users u SET itop_person_id = c.itop_id
FROM contacts c
WHERE u.email IS NOT NULL AND u.email != '' AND LOWER(u.email) = LOWER(c.email) AND c.itop_id IS NOT NULL;

SELECT COUNT(*) as users_linked FROM users WHERE itop_person_id IS NOT NULL;
SELECT COUNT(*) as users_total FROM users;
