-- Migration: support "bind device first, then set child profile"
-- Target: MySQL 8.x

-- 1) Add owner_user_id on device_bindings.
ALTER TABLE device_bindings
    ADD COLUMN owner_user_id BIGINT NULL AFTER device_id;

-- 2) Backfill owner_user_id from active parent-child relation (prefer primary relation).
UPDATE device_bindings b
SET owner_user_id = (
    SELECT r.user_id
    FROM parent_child_relations r
    WHERE r.child_id = b.child_id
      AND r.status = 1
    ORDER BY r.is_primary DESC, r.id ASC
    LIMIT 1
)
WHERE b.owner_user_id IS NULL;

-- 3) Fallback backfill from latest bind history.
UPDATE device_bindings b
SET owner_user_id = (
    SELECT h.bound_by_user_id
    FROM device_bind_history h
    WHERE h.device_id = b.device_id
    ORDER BY h.bound_at DESC, h.id DESC
    LIMIT 1
)
WHERE b.owner_user_id IS NULL;

-- 4) Ensure no NULL owner before setting NOT NULL.
-- If this query returns rows, handle manually before continuing:
-- SELECT id, device_id, child_id FROM device_bindings WHERE owner_user_id IS NULL;

-- 5) Make schema changes for new flow.
ALTER TABLE device_bindings
    MODIFY COLUMN owner_user_id BIGINT NOT NULL;

ALTER TABLE device_bindings
    MODIFY COLUMN child_id BIGINT NULL;

ALTER TABLE device_bindings
    ADD INDEX idx_device_bindings_owner_user_id (owner_user_id);

ALTER TABLE device_bind_history
    MODIFY COLUMN child_id BIGINT NULL;
