-- Migration 153: Multiple AnyDesk IDs per technician
-- Replaces the single anydesk_id column on users with a dedicated table

CREATE TABLE IF NOT EXISTS user_anydesk_ids (
    id          SERIAL PRIMARY KEY,
    user_id     INTEGER NOT NULL REFERENCES users(user_id) ON DELETE CASCADE,
    anydesk_id  VARCHAR(50) NOT NULL,
    label       VARCHAR(100),          -- optional label, e.g. "Privat laptop", "Kontor-PC"
    created_at  TIMESTAMP DEFAULT NOW(),
    UNIQUE (user_id, anydesk_id)
);

CREATE INDEX IF NOT EXISTS idx_user_anydesk_ids_user      ON user_anydesk_ids(user_id);
CREATE INDEX IF NOT EXISTS idx_user_anydesk_ids_anydesk_id ON user_anydesk_ids(anydesk_id);

-- Migrate existing single anydesk_id values from users table
INSERT INTO user_anydesk_ids (user_id, anydesk_id, label)
SELECT user_id, anydesk_id, 'Primær'
FROM users
WHERE anydesk_id IS NOT NULL AND anydesk_id != ''
ON CONFLICT DO NOTHING;
