﻿DELIMITER $$

CREATE PROCEDURE `sp_add_resource`(
    IN p_admin_user_id INT,
    IN p_actor_description VARCHAR(100),
    IN p_category_id TINYINT UNSIGNED,
    IN p_resource_code VARCHAR(100),
    IN p_manufacturer VARCHAR(100),
    IN p_resource_name VARCHAR(100),
    IN p_serial_num VARCHAR(200),
    IN p_spec_value DECIMAL(10, 2),
    IN p_spec_unit TINYINT UNSIGNED,
    IN p_user_id BIGINT,
    IN p_comments VARCHAR(200),
    IN p_purchase_date DATE, -- 파라미터명 및 타입 변경
    IN p_is_locked BOOLEAN,
    OUT p_new_resource_id BIGINT
)
  COMMENT '자산 추가 및 로그 기록'
BEGIN
  DECLARE v_now DATETIME DEFAULT NOW(); -- register_date 용

  -- 입력값 검증
  IF p_admin_user_id IS NULL AND p_actor_description IS NULL THEN
    SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = '작업 주체 정보(관리자 ID 또는 프로세스 설명)는 필수입니다.';
  END IF;
  IF p_resource_name IS NULL OR p_resource_name = '' THEN
     SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = '제품명은 필수입니다.';
  END IF;
   IF p_serial_num IS NOT NULL AND p_serial_num != '' AND EXISTS (SELECT 1 FROM resource_info WHERE serial_num = p_serial_num) THEN
     SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = '이미 등록된 시리얼 번호입니다.';
   END IF;


  -- 트랜잭션 시작
  START TRANSACTION;
    INSERT INTO resource_info (
      category_id, resource_code, manufacturer, resource_name, serial_num,
      spec_value, spec_unit, user_id, comments, purchase_date, register_date, is_locked
      -- update_date는 ON UPDATE CURRENT_TIMESTAMP 로 자동 관리됨
    ) VALUES (
      p_category_id, p_resource_code, p_manufacturer, p_resource_name, p_serial_num,
      p_spec_value, p_spec_unit, p_user_id, p_comments, p_purchase_date, v_now, p_is_locked
    );
    SET p_new_resource_id = LAST_INSERT_ID();

    INSERT INTO log_add_resource (
      log_date, admin_user_id, actor_description, resource_id, category_id, resource_code,
      manufacturer, resource_name, serial_num, spec_value, spec_unit, user_id, comments,
      purchase_date, register_date -- 컬럼명 변경 반영
    ) VALUES (
      v_now, p_admin_user_id, p_actor_description, p_new_resource_id, p_category_id, p_resource_code,
      p_manufacturer, p_resource_name, p_serial_num, p_spec_value, p_spec_unit, p_user_id, p_comments,
      p_purchase_date, v_now -- 컬럼명 변경 반영
    );
  COMMIT;
END
$$

DELIMITER ;