﻿DELIMITER $$

CREATE PROCEDURE `sp_update_resource`(
    IN p_admin_user_id INT,
    IN p_actor_description VARCHAR(100),
    IN p_resource_id BIGINT,
    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
)
  COMMENT '자산 정보 수정 및 로그 기록'
BEGIN
  -- DECLARE v_original_create_date DATETIME; -- register_date로 대체
  DECLARE v_now DATETIME DEFAULT NOW();

  -- 입력값 검증
  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 AND resource_id != p_resource_id) THEN
     SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = '이미 다른 자산에서 사용 중인 시리얼 번호입니다.';
   END IF;

  -- 트랜잭션 시작
  START TRANSACTION;
    -- 자산 정보 업데이트 (update_date는 자동 업데이트)
    UPDATE resource_info SET
      category_id = p_category_id,
      resource_code = p_resource_code,
      manufacturer = p_manufacturer,
      resource_name = p_resource_name,
      serial_num = p_serial_num,
      spec_value = p_spec_value,
      spec_unit = p_spec_unit,
      user_id = p_user_id,
      comments = p_comments,
      purchase_date = p_purchase_date,
      is_locked = p_is_locked
      -- register_date는 수정하지 않음
    WHERE resource_id = p_resource_id;

    -- 로그 기록 (변경 후 정보만 기록)
    INSERT INTO log_update_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 -- 컬럼명 변경 반영
    ) VALUES (
      v_now, p_admin_user_id, p_actor_description, p_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 -- 컬럼명 변경 반영
    );
  COMMIT;
END
$$

DELIMITER ;