-- 000004_seed_admin.up.sql

-- Use DO block for variable dependency and idempotency
DO $$
DECLARE
    v_role_id UUID;
    v_user_id UUID;
BEGIN
    -- 1. Ensure Admin Role exists
    INSERT INTO sys_roles (name, role_key, data_scope, status)
    VALUES ('超级管理员', 'admin', '1', '0')
    ON CONFLICT DO NOTHING;
    
    -- Retrieve role ID (whether inserted or existing)
    -- Note: Since we don't have a unique constraint on role_key in the schema (schema definition in 000003), 
    -- we rely on logic. Ideally role_key should be unique.
    -- Let's try to select it.
    SELECT id INTO v_role_id FROM sys_roles WHERE role_key = 'admin' LIMIT 1;

    -- 2. Ensure Admin User exists
    INSERT INTO users (username, password, name, role, status)
    VALUES ('admin', 'admin123', '系统管理员', 'ADMIN', '0')
    ON CONFLICT (username) DO NOTHING;

    SELECT id INTO v_user_id FROM users WHERE username = 'admin' LIMIT 1;

    -- 3. Link User and Role
    IF v_role_id IS NOT NULL AND v_user_id IS NOT NULL THEN
        INSERT INTO sys_user_roles (user_id, role_id)
        VALUES (v_user_id, v_role_id)
        ON CONFLICT DO NOTHING;
    END IF;
END $$;
