﻿DELIMITER $$

SET @saved_sql_mode = @@sql_mode
$$
SET @@sql_mode = 'NO_AUTO_VALUE_ON_ZERO'
$$
CREATE PROCEDURE `sp_delete_resource`(
    IN p_admin_user_id INT,
    IN p_actor_description VARCHAR(100),
    IN p_resource_id BIGINT
)
  COMMENT '자산 삭제 및 로그 기록'
BEGIN
  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 NOT EXISTS (SELECT 1 FROM resource_info WHERE resource_id = p_resource_id) THEN
    SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = '삭제할 자산을 찾을 수 없습니다.';
  END IF;

  -- 트랜잭션 시작
  START TRANSACTION;
    -- 로그 기록 (삭제 전에!)
    INSERT INTO log_delete_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 -- 컬럼명 변경 반영
    )
    SELECT
      v_now, p_admin_user_id, p_actor_description, resource_id, category_id, resource_code,
      manufacturer, resource_name, serial_num, spec_value, spec_unit, user_id, comments,
      purchase_date, register_date -- 컬럼명 변경 반영
    FROM resource_info WHERE resource_id = p_resource_id;

    -- 자산 삭제
    DELETE FROM resource_info WHERE resource_id = p_resource_id;
  COMMIT;
END
$$

DELIMITER ;