﻿DELIMITER $$

SET @saved_sql_mode = @@sql_mode
$$
SET @@sql_mode = 'NO_AUTO_VALUE_ON_ZERO'
$$
CREATE PROCEDURE `sp_add_user`(
    IN p_admin_user_id INT,
    IN p_actor_description VARCHAR(100),
    IN p_display_name VARCHAR(100), -- 파라미터명 변경
    IN p_account_name VARCHAR(255), -- 파라미터명 변경
    IN p_group_id BIGINT,
    OUT p_new_user_id BIGINT,
    OUT p_result_message VARCHAR(255)
)
  COMMENT '사용자 추가 및 로그 기록'
BEGIN
  DECLARE v_existing_user_id BIGINT DEFAULT NULL;
  DECLARE v_now DATETIME DEFAULT NOW();

  DECLARE EXIT HANDLER FOR SQLEXCEPTION
  BEGIN
    GET DIAGNOSTICS CONDITION 1 @sqlstate = RETURNED_SQLSTATE, @errno = MYSQL_ERRNO, @text = MESSAGE_TEXT;
    ROLLBACK;
    SET p_new_user_id = NULL;
    SET p_result_message = CONCAT('DB 오류 (', @errno, '): ', @text);
  END;

  -- 입력값 검증
  IF p_admin_user_id IS NULL AND p_actor_description IS NULL THEN
    SET p_new_user_id = NULL;
    SET p_result_message = '작업 주체 정보는 필수입니다.';
    -- RETURN; -- ★ 제거
  ELSEIF p_account_name IS NULL OR p_account_name = '' THEN
    SET p_new_user_id = NULL;
    SET p_result_message = '계정 이름은 필수입니다.';
    -- RETURN; -- ★ 제거
  ELSE
    -- 계정 이름 중복 검사
    SELECT user_id INTO v_existing_user_id FROM user_info WHERE LOWER(account_name) = LOWER(p_account_name) LIMIT 1;
    IF v_existing_user_id IS NOT NULL THEN
      SET p_new_user_id = NULL;
      SET p_result_message = CONCAT('이미 사용 중인 계정 이름입니다: ', p_account_name);
      -- RETURN; -- ★ 제거
    ELSE
      -- 모든 검증 통과, 트랜잭션 시작
      START TRANSACTION;
        INSERT INTO user_info (display_name, account_name, group_id)
          VALUES (p_display_name, p_account_name, p_group_id);
        SET p_new_user_id = LAST_INSERT_ID();

        INSERT INTO log_add_user (log_date, admin_user_id, actor_description, user_id, display_name, account_name, group_id)
          VALUES (v_now, p_admin_user_id, p_actor_description, p_new_user_id, p_display_name, p_account_name, p_group_id);
      COMMIT;
      SET p_result_message = CONCAT('사용자 "', IFNULL(p_display_name, p_account_name), '" (ID: ', p_new_user_id, ') 추가 완료.');
    END IF; -- 계정 중복 검사 IF 종료
  END IF; -- 입력값 검증 IF 종료

END
$$

DELIMITER ;